imstillalive imstillalive - 1 month ago 9
iOS Question

Swift - Get an array of strings from JSON using SwiftyJSON

[
{
"content": "Hello!",
"images": [
{
"url": "http://url1.com"
},
{
"url": "http://url2.com"
},
{
"url": "http://url3.com"
}
]
}
]


How can I get an array of image urls using
SwiftyJSON
?

This is what I tried and did not work.

for (key, subJson) in json["images"] {
if let url = subJson["url"].string {
print(url)
}
}


If I understand correctly, my "images" JSON contains an array of dictionaries but my code is for an array of strings. What can i do to get an array of url strings?

Answer

According to your JSON

if let images = json[0]["images"].array {
  for image in images {
    if let url = image["url"].string {
      print(url)
    }
  }
}

The root object is an array [], the dictionary ({}) containing images is in the first object of the root array.

You can get an array of the URLs with

if let images = json[0]["images"].array {
  let imageArray = images.flatMap{ $0["url"].string }
  print(imageArray)
}
Comments