Search code examples
arraysjsonswiftnsarrayswift5

Reading Json arrays with Swift 5


I have a following json while after i make an api call

[{"breeds":
[{"weight":{"imperial":"7 - 14","metric":"3 - 6"},"id":"ebur","description":" Something ","child_friendly":4,}]
,"url":"https://cdn2.thecatapi.com/images/YOjBThApG.jpg","width":2838,"height":4518}]

As you can see, there are nested arrays and the output from this api call I want to get Id and url. I process my dataTask output just like that

let jsonResponse = try? JSONSerialization.jsonObject(with: data!, options: [])
guard let jsonArray = jsonResponse as? [[String: Any]] else {
                          return
                    }

So i can access url with no problem print(jsonArray[0]["url"]) and i can also do jsonArray[0]["breeds"]. However, I cant do jsonArray[0]["breeds"]["decription"] or jsonArray[0]["breeds"]["id"]. because i get the following error Value of type 'Any?' has no subscripts I suspect that the problem is in [[String: Any]]. How would i change my jsonResponse conversion to an array to get the right output for the calls


Solution

  • You have to cast any subscripted value

    if let breeds = jsonArray.first?["breeds"] as? [[String:Any]],
       let description = breeds.first?["description"] as? String {
         print(description)
    }