Joshua Ziering Joshua Ziering - 6 months ago 10
Swift Question

How Can I Parse Json In Json With SwiftyJSON?

I am returning the following JSON from an API. In my database, I store a list in JSON already. Thus, it gives us a string of JSON inside JSON. How can I access these as objects in Swift? More to the point: How can I parse JSON inside of JSON?

{
"checklists": [
{
"id": 1,
"account_id": 15,
"user_id": 15,
"object_id": 21,
"checklist": "[{\"title\":\"Test\",\"summary\":\"Test 12\"},{\"title\":\"Test 2 \",\"summary\":\"Test 123\"}]",
"title": "High Altitude Operations",
"type": "other",
"LastHistory": null,
"CleanArray": [
{
"title": "Test",
"summary": "Test 12"
},
{
"title": "Test 2 ",
"summary": "Test 123"
}
]
}
]
}

Answer

First, decode the main object.

Let's say data is the JSON in your question:

let json = JSON(data: data)

To get the content of the checklist key inside the array inside the checklists key, we can use SwiftyJSON's key path subscripting like this:

let checkList = json["checklists",0,"checklist"]
print(checkList)

Prints:

[{"title":"Test","summary":"Test 12"},{"title":"Test 2 ","summary":"Test 123"}]

This is your inner JSON as a String.

Make it data, then do the same process and access the array content:

if let json2String = checkList.string, 
        data2 = json2String.dataUsingEncoding(NSUTF8StringEncoding) {
    let json2 = JSON(data: data2)
    let checkList2 = json2[0]
    let title = checkList2["title"]
    print(title)
}

Prints:

Test

Note that I've used key path subscripting for this example, but usual techniques like simple subscripting, loops and map/flatMap/etc also work:

let mainChecklists = json["checklists"]
for (_, content) in mainChecklists {
    if let innerString = content["checklist"].string,
            data2 = innerString.dataUsingEncoding(NSUTF8StringEncoding) {
        let json2 = JSON(data: data2)
        for (_, innerChecklist) in json2 {
            let title = innerChecklist["title"]
            print(title)
        }
    }
}

Prints:

Test
Test 2