How Can I Parse Json In Json With SwiftyJSON?

只谈情不闲聊 提交于 2019-12-02 03:22:59

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!