How to loop through JSON with SwiftyJSON?
Asked Answered
M

5

36

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 ?

Maurreen answered 6/2, 2015 at 12:36 Comment(0)
C
79

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)
        }
    }
}
Colostomy answered 6/2, 2015 at 15:28 Comment(5)
when I try looping through my dictionary of [String: JSON] I get the error: '[String : JSON]?' does not have a member named 'Generator'Oceanid
because it's optionalObedience
@Colostomy I used your method and it works, but I'm just not sure if I'm being efficient or not. If you had multiple items to capture (ex. title, author, comment) would you simply repeat ` if let <<newItem>> = item["<<newItem>>"].string {}` for each of them?Dandelion
@Dandelion Basically, yes. But if you mind "efficiency", IMO you should not use SwiftyJSON. see: SwiftyJSON Performance IssuesColostomy
@Colostomy - Very interesting. For my initial application, SwiftyJSON should be ok, but I will bookmark that SO conversation for future consideration. Thanks.Dandelion
S
11

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!)
                }
            }
        }
   }
Sectorial answered 9/7, 2015 at 21:5 Comment(1)
The correct syntax is for (key, subJson):(String, JSON) in jsonInerrant
B
8

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

Bramwell answered 6/2, 2015 at 12:48 Comment(1)
Please tick that green label on the left if I helped. Thanks!Bramwell
R
1

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
}
Rosalba answered 1/5, 2015 at 14:3 Comment(2)
He stated in the question that he checked the docs. Not very helpful imo. Sorry.Harlotry
This helped me quite a bit. ThanksMcmahon
F
0

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

Favor answered 21/1, 2019 at 1:52 Comment(1)
While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer - From ReviewKebab

© 2022 - 2024 — McMap. All rights reserved.