NSDictionary to json string to json object using SwiftyJSON

Upvote picture Upvote · Nov 11, 2014 · Viewed 23.9k times · Source

I have a use case where I have an array of dictionaries and I need them as a json object:

var data = [Dictionary<String, String>]()
//append items 
var bytes = NSJSONSerialization.dataWithJSONObject(data, options: NSJSONWritingOptions.allZeros, error: nil)
var jsonObj = JSON(NSString(data: bytes!, encoding: NSUTF8StringEncoding)!)

println(jsonObj)
println(jsonObj[0])

The first print statement gives me

[
    {"price":"1.20","city":"Foo","_id":"326105","street":"One"},
    {"price":"1.20","city":"Bar","_id":"326104","street":"Two"}
]

the second

null

but I would expect it to return the first element in the json array. What I am doing wrong?

Answer

Jeffery Thomas picture Jeffery Thomas · Nov 11, 2014

According to the docs, this should be all you need.

var data = [Dictionary<String, String>]()
//append items 
var jsonObj = JSON(data)

println(jsonObj)
println(jsonObj[0])

Are you having a problem with converting an array directly into a JSON object?