Swift JSON add new key to existing dictionary
Asked Answered
U

2

6

I'm using Alamofire and SwiftyJSON to get and manage data from an API After making my initial request I end up with nested collection of type JSON

According to SwiftyJSON I can loop through data like so https://github.com/SwiftyJSON/SwiftyJSON#loop

for (key: String, subJson: JSON) in json {
   //Do something you want
}

Again, according to SwiftyJSON I should be able to set new values like so: https://github.com/SwiftyJSON/SwiftyJSON#setter

json["name"] = JSON("new-name")

I have a nested collection of data and I can dig in as deep as I want, but I'm unable to alter the object and set new key:value pair. How would I got about doing this in Swift?

Here's my code :

            for (key: String, stop: JSON) in stops {
                var physicalStops = stop["physicalStops"]
                for (key: String, physicalStop: JSON) in physicalStops {
                    println("Prints out \(physicalStop) just fine")
                   // physicalStop["myNewkey"] = "Somevalue" // DOES NOT WORK (@lvalue is not identical to 'JSON)
                   // physicalStop["myNewkey"] = JSON("Somevalue") //SAME Story
                }
            }

Basically I'd like to keep the very same structure of the original JSON object, but add additional key:value on the second level nesting for each sub object.

Universalism answered 28/2, 2015 at 10:51 Comment(0)
S
7

First, you can use var in for-loop to make value modifiable inside the loop. However, JSON is struct so it behaves as a value type, so in your nested example, you have to reassign also the child JSON to the parent JSON otherwise it just modifies the value inside the loop but not in the original structure

var json: JSON = ["foo": ["amount": 2], "bar": ["amount": 3]]
for (key: String, var item: JSON) in json {
     println("\(key) -> \(item)")
     item["price"] = 10
     json[key] = item
}
println(json) 
Shane answered 28/2, 2015 at 11:9 Comment(0)
A
1

Below is code that runs fine in Swift 2 playground and does not require Swifty:

var json: [String:AnyObject] = ["foo": ["amount": 2], "bar": ["amount": 3]]
for (key,item) in json {
     print("\(key) -> \(item)")
     let newItem = ["price": 10]
     json[key] = newItem
}
print(json)
Allianora answered 4/11, 2016 at 19:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.