Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I manipulate nested dictionaries in Swift, e.g. JSON data?

Tags:

json

swift

I'm using NSJSONSerialization to parse JSON in a Swift application. However, the returned dictionary consists of a complicated, deeply nested structure, making it impractical to have very long type declarations (e.g. Dictionary<String, Array<Dictionary<String, ....>>).

Is there a good way of working with such a structure in Swift, where the collection's structure is very complicated and its types aren't known until runtime?

like image 213
Bill Avatar asked Jun 06 '14 03:06

Bill


3 Answers

Just grab a reference to your json data as an NSDictionary:

var dict: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

then you can reference it using subscripts:

var myValue: NSString = dict["level1"]["level2"]
like image 163
Ben Gottlieb Avatar answered Nov 13 '22 10:11

Ben Gottlieb


myDictionary["accounts"] might be an optional. Try: myDictionary["accounts"]?["active"]?

like image 5
GK100 Avatar answered Nov 13 '22 11:11

GK100


In Obj-C we could write,

cityName = myDictionary[@"photos"][@"region"][@"city"]

As several here have discovered, the above does not apply in Swift, at least it never has for me.

Here's how you do this in Swift for accessing three indices in an NSDictionary for a String,

let cityName = ((myDictionary!["photos"] as NSDictionary)["region"]! as NSDictionary)["city"]! as String`

I hope that in the next update to Swift all of that can be reduced to what we had in Obj-C.

like image 4
Jim Hillhouse Avatar answered Nov 13 '22 10:11

Jim Hillhouse