Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through JSON with SwiftyJSON?

I have a json that I could parse with SwiftyJSON :

if let title = json["items"][2]["title"].string {      println("title : \(title)") } 

Works perfectly.

But I couldn't loop through it. I tried two methods, the first one is

// TUTO : //If json is .Dictionary for (key: String, subJson: JSON) in json {     ... } // WHAT I DID : for (key: "title", subJson: json["items"]) in json {     ... } 

XCode didn't accept the for loop declaration.

The second method :

// TUTO : if let appArray = json["feed"]["entry"].arrayValue {      ... } // WHAT I DID : if let tab = json["items"].arrayValue {      ... } 

XCode didn't accept the if statement.

What am I doing wrong ?

like image 579
Cherif Avatar asked Feb 06 '15 12:02

Cherif


2 Answers

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)         }     } } 
like image 127
rintaro Avatar answered Sep 17 '22 23:09

rintaro


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!)                 }             }         }    } 
like image 42
CularBytes Avatar answered Sep 20 '22 23:09

CularBytes