jeremykrall
jeremykrall

Reputation: 181

Swift and accessing nested JSON collections

I am accessing a CMS with a pre-baked JSON output and it uses the following data structure. I am struggling to get down into the nested collections to get the version or loop through the categories.

{
    results: [
        {
            pageData: {
                info: {
                    version: "1"
                },
                categories: [
                    {
                        name: "Cat 1"
                    },
                    {
                        name: "Cat 2"
                    }
                ]
            }
        }
    ]
}

Here is the code I was attempting to use. Any help is appreciated!

guard let json = json, let results = json["results"], let pageData = results["pageData"], let info = pageData["info"] as? [String:Int], let version = info["version"], 
    let categories = Category.getCategories(json: json) else {
    self.completionParse(RequestResult.errorParsing, self.categoriesResult)
    return
}

Upvotes: 1

Views: 3561

Answers (2)

Anil Kukadeja
Anil Kukadeja

Reputation: 1358

Tested below code on playground. This code is in latest swift 3.

if let dictResponse = json as? [String:Any] {
    // This will get entire dictionary from your JSON.
    if let results = dictResponse["results"] as? [[String:Any]]{
        if let pageData = results.first? ["pageData"] as? [String:Any]{
            if let info = pageData["info"] as? [String:Any]{
                if let version = info["version"] as? String{
                    print(version)
                    // This will print 1
                }
            }

            if let categories = pageData["categories"] as? [[String:Any]]{
                // This will give you a category array. Later on you can iterate and get the dictionary’s value of each element.
                for categoriesObj in categories.enumerated(){
                    if let name = categoriesObj.element["name"]{
                        print(name)
                    }
                }
            }           
        }   
    }
}

Upvotes: 2

Nirav D
Nirav D

Reputation: 72410

To access the info and categories dictionaries you need to first access results Array and pageData that is inside the first object of results array.

guard let json = json, let results = json["results"] as? [[String:Any]], 
    let firstDic = results.first, let pageData = firstDic["pageData"] as? [String:Any],
    let info = pageData["info"] as? [String:Int], let version = info["version"], 
    let categories = Category.getCategories(json: pageData) else {

    self.completionParse(RequestResult.errorParsing, self.categoriesResult)
    return
}

Upvotes: 4

Related Questions