NSDictionary to json string to json object using SwiftyJSON
Asked Answered
L

2

7

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?

Libertylibia answered 10/11, 2014 at 23:41 Comment(1)
I know nothing of Swifty JSON, but I would surmise that jsonObj is an object whose description displays the data you see. But the object is not an array, and the [0] operator bounces off.Allembracing
G
24

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?

Gladi answered 11/11, 2014 at 1:27 Comment(0)
A
8

I'm not sure what method you have on the 4th line there (JSON) but I got your code to work using NSJSONSerialization.JSONObjectWithData seen below:

var data = [Dictionary<String, String>]()
data.append(["price":"1.20","city":"Foo","_id":"326105","street":"One"])
data.append(["price":"1.20","city":"Bar","_id":"326104","street":"Two"])

let bytes = try! NSJSONSerialization.dataWithJSONObject(data, options: NSJSONWritingOptions.PrettyPrinted)
var jsonObj = try! NSJSONSerialization.JSONObjectWithData(bytes, options: .MutableLeaves) as! [Dictionary<String, String>]

print(jsonObj)
print(jsonObj[0])

... with output ...

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

"[price: 1.20, city: Foo, _id: 326105, street: One]"

Edit: I see now the tag for swifty-json. I'm not familiar with that, but the code I included above works with the built in methods.

Ayr answered 11/11, 2014 at 1:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.