How to loop through JSON with SwiftyJSON?

北战南征 提交于 2019-11-28 17:13:32

If you want loop through json["items"] array, try:

for (key, subJson) in json["items"] {
    if let title = subJson["title"].string {
        println(title)
    }
}

As for the second method, .arrayValue returns non Optional array, you should use .array instead:

if let items = json["items"].array {
    for item in items {
        if let title = item["title"].string {
            println(title)
        }
    }
}

I Find it a bit strange explained myself, because actually using:

for (key: String, subJson: JSON) in json {
   //Do something you want
}

gives syntax errors (in Swift 2.0 atleast)

correct was:

for (key, subJson) in json {
//Do something you want
}

Where indeed key is a string and subJson is a JSON object.

However I like to do it a little bit different, here is an example:

//jsonResult from API request,JSON result from Alamofire
   if let jsonArray = jsonResult?.array
    {
        //it is an array, each array contains a dictionary
        for item in jsonArray
        {
            if let jsonDict = item.dictionary //jsonDict : [String : JSON]?
            {
                //loop through all objects in this jsonDictionary
                let postId = jsonDict!["postId"]!.intValue
                let text = jsonDict!["text"]!.stringValue
                //...etc. ...create post object..etc.
                if(post != nil)
                {
                    posts.append(post!)
                }
            }
        }
   }
Dhruv Ramani

In the for loop, the type of key can't be of the type "title". Since "title" is a string, go for : key:String. And then Inside the Loop you can specifically use "title" when you need it. And also the type ofsubJson has to be JSON.

And Since a JSON file can be considered as a 2D array, the json["items'].arrayValue will return multiple objects. It is highly advisable to use : if let title = json["items"][2].arrayValue.

Have a look at : https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Types.html

Please check the README

//If json is .Dictionary
for (key: String, subJson: JSON) in json {
   //Do something you want
}

//If json is .Array
//The `index` is 0..<json.count's string value
for (index: String, subJson: JSON) in json {
    //Do something you want
}

you can iterate through the json by:

for (_,subJson):(String, JSON) in json {

   var title = subJson["items"]["2"]["title"].stringValue

   print(title)

}

have a look at the documentation of SwiftyJSON. https://github.com/SwiftyJSON/SwiftyJSON go through the Loop section of the documentation

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