how to add json object to dictionary - swift

when i create output with Alamofire using SwiftyJSON
Alamofire.request(.POST, "http://localhost:8080/ws/automobile/global/auction/latest/venues").responseJSON() {
(request, response, jsonData, error) in
var venues = JSON(jsonData!)
println(venues)
}
it appear like this in console
{
"C2058" : [
"LAA Okayama"
],
"C2062" : [
"NAA Osaka"
],
"C2035" : [
"JU Ibaraki"
],
"C2526" : [
"SMAP Fukuoka Nyusatsu"
],
"C2530" : [
"SMAP Tokyo Nyusatsu"
],
"C2074" : [
"TAA Tohoku"
],
"C2008" : [
"BCN"
],
"C2012" : [
"CAA Tokyo"
],
"C2503" : [
"L-Up PTokyoNyusatsu"
],
"C2047" : [
"JU Shizuoka"
],
"C2051" : [
"JU Yamaguchi"
],
"C2086" : [
"USS Saitama"
]
}
I want to add this to my new dictionary to use in UIPickerView,any suggestion how to do it.I am newbie to swift,code answer is really appreciated.Thank you.
What i Really want it dictionary like this
["C2047":"L-Up PTokyoNyusatsu","C2086":"USS Saitama".......]
Please help!!!

Don't know whether this is what you want:
var result = [String:String]()
let d = json.dictionaryValue
for (k, v) in d {
result[k] = v.arrayValue[0].stringValue
}
println(result)

From the example you've given:
"C2058" : [
"LAA Okayama"
],
"C2062" : [
"NAA Osaka"
],
"C2035" : [
"JU Ibaraki"
]
Those "C2058","C2062" are the key of Dictionary. And ["LAA Okayama"] is a String inside NSArray.
So, if you want to get the String inside NSArray. First, use the key to get value in Dictionary. Then, use NSArray to get the String.
it would like this:
var dict:NSDictionary=jsonData as Dictionary
var arr=dict["C2058"] as NSArray
and
println(arr[0]) //you'll see LAA Okayama

Related

Adding elements to JSON array using circe and scala

I have a JSON string as the following:
{
"cars": {
"Nissan": [
{"model":"Sentra", "doors":4},
{"model":"Maxima", "doors":4},
{"model":"Skyline", "doors":2}
],
"Ford": [
{"model":"Taurus", "doors":4},
{"model":"Escort", "doors":4}
]
}
}
I would like to add a new cars brand (in addition to Nissan and Ford), using circe at scala.
How could I do it?
Thank you in advance.
You can modify JSON using cursors. One of the possible solutions:
import io.circe._, io.circe.parser._
val cars: String = """
{
"cars": {
"Nissan": [
{"model":"Sentra", "doors":4},
{"model":"Maxima", "doors":4},
{"model":"Skyline", "doors":2}
],
"Ford": [
{"model":"Taurus", "doors":4},
{"model":"Escort", "doors":4}
]
}
}"""
val carsJson = parse(cars).getOrElse(Json.Null)
val teslaJson: Json = parse("""
{
"Tesla": [
{"model":"Model X", "doors":5}
]
}""").getOrElse(Json.Null)
val carsCursor = carsJson.hcursor
val newJson = carsCursor.downField("cars").withFocus(_.deepMerge(teslaJson)).top
Here we just go down to cars field, "focus" on it and pass the function for modifying JSON values. Here deepMerge is used.
newJson will be look as follows:
Some({
"cars" : {
"Tesla" : [
{
"model" : "Model X",
"doors" : 5
}
],
"Nissan" : [
{
"model" : "Sentra",
"doors" : 4
},
{
"model" : "Maxima",
"doors" : 4
},
{
"model" : "Skyline",
"doors" : 2
}
],
"Ford" : [
{
"model" : "Taurus",
"doors" : 4
},
{
"model" : "Escort",
"doors" : 4
}
]
}
})

How can create assoc 3D Array of Array?

I tried create Array 3D but i still don't know how to create one ?
var array = [
"10001": [
"last_index": 0, //Int
"conteiner": [
"id_from": 321, // Int
"val2": "string text" // String
]
]
]
This works for me in Swift 2.0:
let array : [String : [String : Any]] = [
"10001": [
"last_index": 0, //Int
"conteiner": [
"id_from": 321 as Any, // Int
"val2": "string text" as Any // String
]
]
]
array["10001"]?["last_index"] // 0

Update Object at Specific Array Index in MongoDB

I have a collection of the form
{ id : 1,
data: [ [ { name : "alice" }, { name : "bob" } ],
[ { name : "dan" }, { name : "rob" } ] ] }
and the structure of the array has meaning. How would I update the first element ([0][0]) and set name = "alex". I've seen many questions addressing how to update array elements that match a query but not specific elements. To be clear, after the update, the record should look like this:
{ id : 1,
data: [ [ { name : "alex" }, { name : "bob" } ],
[ { name : "dan" }, { name : "rob" } ] ] }
Assuming, you have created the structure with some purpose, which ideally becomes tougher to query, you could update it by specifying the index explicitly:
db.collection.update({"id":1},{$set:{"data.0.0.name":"alex"}})
If we don't have a fixed position and is known at runtime or Dynamic
then this approach works perfectly
var setObject = {};
setObject["board."+ x +"."+ y] = player;
gamesColl.update({_id: realId},{
$set:setObject
}, function(err,doc){
console.log(err,doc);
});
you can go further!!
if you want to paste indexes as a variable use string template like this
db.collection.update({"id":1},{$set:{[`data.${index}.${index}.name`]:"alex"}})

NSPredicate Filtered childs in array

Good day, I'm using new language Apple Swift and using the NSArray:
[
{
"Section" : "Title1",
"Items" :
[
{"Nr" : "101"},
{"Nr" : "201"},
{"Nr" : "301"},
{"Nr" : "401"}
]
},
{
"Section" : "Title2",
"Items" :
[
{"Nr" : "102"},
{"Nr" : "202"},
{"Nr" : "302"}
]
},
{
"Section" : "Title3",
"Items" :
[
{"Nr" : "1102"},
{"Nr" : "2102"},
{"Nr" : "3102"}
]
}
]
I want to use search, and display only content what is found
As I understand I have to use the "filteredArrayUsingPredicate" and NSPredicate in swift, so my sample is:
var arr:NSArray = [...] // My array sample goes here
var pre:NSPredicate = NSPredicate(format: "ANY Items.Nr BEGINSWITH[c] %#", argumentArray: ["20"]) // We a going to search "20" in /Items/Nr
var result:NSArray = arr.filteredArrayUsingPredicate(pre)
This is working correct but result is not what I need:
result =
[
{
"Section" : "Title1",
"Items" :
[
{"Nr" : "101"},
{"Nr" : "201"},
{"Nr" : "301"},
{"Nr" : "401"}
]
},
{
"Section" : "Title2",
"Items" :
[
{"Nr" : "102"},
{"Nr" : "202"},
{"Nr" : "302"}
]
}
]
It is display me all section what is contains Imtes with Nr started with "20"
And my question is how to do filter also in Items? The result what I need is have to be:
result =
[
{
"Section" : "Title1",
"Items" :
[
{"Nr" : "201"}
]
},
{
"Section" : "Title2",
"Items" :
[
{"Nr" : "202"}
]
}
]
I tried to use the SUBQUERY:
"SUBQUERY(Items, $x, $x.Nr BEGINSWITH[c] %#).#count > 0"
But this return me the same, if it can calculate the Items, then I thought that it can display me Items/Nr what I found, but I dont know how to write this correct. :)
Oh, hang on. I just re-read your question, editing now
To answer your requirement of filtering the sub arrays. Your data model is getting far too complex to still be using generic objects. You should think about setting up an actual data structure with custom objects. You can then offload a lot of the work to these objects instead of putting all the work in one place.
Just trying to find the best way to do this (without a custom data model).
P.S. make a custom data model :)
OK, here we go
I made this a lot easier by wrapping your generic data up into a struct...
struct Item {
let section: String
let items: [[String: String]]
}
It still feels wrong having an array of dictionaries where each dictionary has only one key and it's always the same. Really it should just be an array of strings.
Anyway...
Create the array like so...
let items: [Item] = [
Item(section: "Title1", items: [["Nr" : "101"], ["Nr" : "201"], ["Nr" : "301"], ["Nr" : "401"]]),
Item(section: "Title2", items: [["Nr" : "102"], ["Nr" : "202"], ["Nr" : "302"]]),
Item(section: "Title3", items: [["Nr" : "1102"], ["Nr" : "2102"], ["Nr" : "3102"]])
]
Or from your data however you have it stored.
Then filter and map it into a new array...
let filteredMappedArray = items.filter {
// this filters the array so that only its containing "20..." are in it.
for dictionary in $0.items {
if let numberString = dictionary["Nr"] {
if (numberString.hasPrefix("20")) {
return true
}
}
}
return false
}.map {
// This maps the array and removes anything that isn't "20..." from the items.
Item(section: $0.section, items: $0.items.filter {
numberDictionary in
if let numberString = numberDictionary["Nr"] {
return numberString.hasPrefix("20")
}
return false
})
}
Then I logged the result...
for item in filteredMappedArray {
println("Section: \(item.section) - Items: \(item.items)")
}
And got this result...
Section: Title1 - Items: [[Nr: 201]]
Section: Title2 - Items: [[Nr: 202]]
There may be better/simpler way to combine everything into one function but this is the easiest way I could find.
If you can change your dictionary array thing...
If item can be defined as...
struct Item {
let section: String
let items: [String]
}
Then the filter-map function would become...
let filteredMappedArray = items.filter {
// this filters the array so that only its containing "20..." are in it.
for numberString in $0.items {
if (numberString.hasPrefix("20")) {
return true
}
}
return false
}.map {
// This maps the array and removes anything that isn't "20..." from the items.
Item(section: $0.section, items: $0.items.filter {$0.hasPrefix("20")})
}
By changing that dictionary array to just an array of strings you're removing a layer of complexity that isn't necessary.

determine which predefined graphical region a user is in using mongodb

using mongo, I would like to compare a user's geo coordinates to a collection of documents each representing a defined geographical boundary. This is what i have thought to do, but cant get working. Other suggestions to get the same result are also welcome.
A document from the collection looks like this (those are manhattan coordinates, if you draw a line in sequence from one coordinate to the next, it wraps manhattan)
{
"__v" : 1,
"_id" : ObjectId("53220803a74a16da9c729202"),
"name" : "Manhattan",
"boundary" : {
"type" : "Polygon",
"coordinates" : [
[
[
-74.01237999999999,
40.69967
],
[
-73.97895,
40.71076
],
[
-73.97169,
40.73049
],
[
-73.92828,
40.79605
],
[
-73.95547999999999,
40.82635
],
[
-74.00901,
40.75431
],
[
-74.01961,
40.7059
]
]
]
}
}
i then use the following query to make my check
db.collection.find( { boundary :
{ $geoIntersects :
{ $geometry :
{ type : "Point" ,
coordinates : [ [user_long, user_lat] ]
} } } } ).exec(function(err, city){
console.log(err, "error");
res.send({agent_count : city});
});