Swift 3 - Add key value to dictionary in parsed JSON Response

时间:2018-02-03 08:29:26

标签: ios json dictionary swift3 key-value

I am calling URL to get a JSON response, an array of dictionaries. I want to append a key:value pair in each dictionary that I get in my response. How do I go about this in swift 3?

For instance, my JSON Response is:

[{"id":"100", "name":"Matt", "phone":"0404040404"}
,{"id":"100", "name":"Sean", "phone":"0404040404"}
, {"id":"100", "name":"Luke", "phone":"0404040404"}]

I want to modify the response to show another key "address", so the output becomes:

[{"id":"100", "name":"Matt", "phone":"0404040404", "address":"TBC"}
,{"id":"100", "name":"Sean", "phone":"0404040404", "address":"TBC"}
, {"id":"100", "name":"Luke", "phone":"0404040404", "address":"TBC"}]

My code for just parsing the response is below, doesn't have the code to append the key:value pair. Can I append while parsing itself?

let Task = URLSession.shared.dataTask(with: URL!) { (Data, response, error) in
            if error != nil {
                print(error)
            } else {
                if let DataContent = Data {
                    do {
                        let JSONresponse = try JSONSerialization.jsonObject(with: DataContent, options: JSONSerialization.ReadingOptions.mutableContainers)
                        print(JSONresponse)

                        for item in JSONresponse as! [Dictionary<String, Any>] {
                            let id = item["id"] as! String
                            let name = item["name"] as! String
                            let phone = item["phone"] as! String         
                        }
                    }
                    catch { }
                }
            }
        }
        Task.resume()

1 个答案:

答案 0 :(得分:0)

To append extra key:value pair in dictionary there are many ways to achieve this. But in your case, it would be better to append key:value just after getting the response from the web service calling. Here is the sample code snippet which can help you.

var aJSONRes = JSONresponse as! [Dictionary<String, Any>]
        for (index,_) in aJSONRes.enumerated() {
            aJSONRes[index]["address"] = "Your address"
        }

Hope this helps you.