Lara Amro Lara Amro - 1 month ago 16
iOS Question

Convert JSON nested objects

I am getting the following JSON from Foursquare API and I have been struggling with extracting the data:

{
"meta":{
"code":200,
"requestId":"58122e59498e5506a1b23580"
},
"response":{
"venues":[
{
"id":"4d56c381a747b60cd4a12c2b",
"name":"Sports Circle",
"contact":{},
"location":{
"lat":31.9,
"lng":35.9,
"labeledLatLngs":[
{
"label":"display",
"lat":31.9,
"lng":35.90
}
],
],
"confident":true
}
}
}


I want to get the
name
in
venues
in addition to the
lat
and
lng
values. I have tried this so far but it gets out of the second if statement at
JVenues
because it is
nil
:

func parseData (JSONData: Data){
do {
var readableJson = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! [String:AnyObject]

if let JResponse = readableJson ["response"] as? [String:AnyObject] {
if let JVenues = JResponse["venues"] as? [String:AnyObject]{
if let JName = JVenues["name"] as? String{
NSLog(JName)
}
}
}
} catch {
print(error)
}
}

Answer

This is what the other answers are getting at. Will probably make more sense if you can see it all laid out...

if let JResponse = readableJson ["response"] as? [String : AnyObject] {
    if let JVenues = JResponse["venues"] as? [[String : AnyObject]] {
        if let JName = JVenues.first?["name"] as? String {
            NSLog(JName)
        }
    }
}

Note this only gets the FIRST name in the array of venues.

A slight modification would allow you to print all the names if there were more venues in your array:

 if let JResponse = readableJson ["response"] as? [String : AnyObject] {
     if let JVenues = JResponse["venues"] as? [[String : AnyObject]] {
         JVenues.forEach({ print("name \($0["name"])") })
     }
 }
Comments