1
[
  {
    "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?

0

1 Answer 1

4

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)
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks! What if I also want a string of url? How can I do that?
I don't understand, the value of url is String.
When I do this let imageString = images.flatMap{ $0["url"].string } I get a 'flatmap produces ... not the expected contextual result of type String!" Sorry. I'm very new to swift.
You wrote: get an array of url strings. This is an array of strings ([String]), not a single string (String).
I understand. Your answer worked perfectly and I already used it. But now I have another JSON that I need to parse. It requires me to get it out as a single String not a [String]. I do not know how to do this and I thought you might so thats why I commented to ask.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.