Suhaib Suhaib - 2 months ago 88
JSON Question

How to print JSON values using a loop in Swift 3?

I got this JSON:

{
cover = {
id = 1;
};
description = "Test"
place = {
id = 11;
location = {
city = Wheatley;
};
name = "Wheatley Provincial Park";
};
},
{
cover = {
id = 2;
};
description = "Cool"
place = {
id = 22;
location = {
city = Wheatley;
};
name = "Wheatley Provincial Park";
};
}


This is my code:

if let fbData = result as? [String : Any] {
print(fbData)

for events in fbData {
print (events["name"] as! String)
//this displays an error
//Type (Key: String, value: Any) has subscript members
}


}

But I don't know how to loop through them

I already tried these solutions but they never worked:

JSON Parsing in Swift 3

Correctly Parsing JSON in Swift 3

Parsing JSON using Swift 3

Answer
if let array = result as? [String : AnyObject]{
    if let fbData = array["data"] as? [[String : AnyObject]] {
        print(fbData)

        for event in fbData {
            print (event["name"] as! String)
        }
    }
}
  1. result is of Any type
  2. Cast it into Dictionary - [String : AnyObject]
  3. Extract data and cast to Array of Dictionaries - [[String : AnyObject]].
Comments