Changerrs
Changerrs

Reputation: 273

Get data out of array of dictionaries from JSON response

I am trying to get data out of an array of nested dictionaries which is the result of a JSON response.

func fetchData() {
    let urlString = "https://global.api.pvp.net/api/lol/static-data/na/v1.2/champion?api_key=\(self.apiKey)"
    let url = URL(string: urlString)

    URLSession.shared.dataTask(with:url!) { (data, response, error) in
        if error != nil {
            print(error ?? "ERROR!")
        } else {
            do {

                let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
                print(parsedData)
                print(parsedData["type"] ?? "")
                print(parsedData["version"] ?? "")

                print(type(of: parsedData))
                print(type(of: parsedData["data"]!))


                //ERROR HERE.
                //"Cannot subscript a value of type '[String, Any]' with an index of type '(String, (String, Any).Type)'
                let innerItem = parsedData["Aatrox", (String, Any)]





            } catch let error as NSError {
                print(error)
            }
        }

    }.resume()

Here is what is printed:

["type": champion, "version": 7.4.3, "data": {
Aatrox =     {
    id = 266;
    key = Aatrox;
    name = Aatrox;
    title = "the Darkin Blade";
};
Ahri =     {
    id = 103;
    key = Ahri;
    name = Ahri;
    title = "the Nine-Tailed Fox";
};
Akali =     {
    id = 84;
    key = Akali;
    name = Akali;
    title = "the Fist of Shadow";
};
Alistar =     {
    id = 12;
    key = Alistar;
    name = Alistar;
    title = "the Minotaur";
};
}]

champion
7.4.3

Dictionary<String, Any>
__NSDictionaryI

I am trying to get the "id" for "Aatrox".

How would i go about doing this?
is it because the type of parsedData["data"]! is __NSDictionaryI??

Thanks for the help.

Upvotes: 0

Views: 1951

Answers (3)

ANSHUL SHAH
ANSHUL SHAH

Reputation: 1

let data : [string:Any] = parsedData.value(key: "data")
let aatrox : [string:Any] = data["Aatrox"]
print("**id**\(aatrox["id"])") 

this thing work for me..

Upvotes: 0

Nirav D
Nirav D

Reputation: 72410

First you need to extract data Dictionary then access other dictionary.

do {
    let parsedData = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]
    if let passDic = parsedData["data"] as? [String:Any],
       let innerItem = passDic["Aatrox"] as? [String: Any] {
          print(innerItem)
    }

} catch  {
     print(error)
}

Upvotes: 4

Tj3n
Tj3n

Reputation: 9923

Seems like it should be let innerItem: [String: Any] = parsedData["Aatrox"]

Upvotes: 0

Related Questions