0

I am trying to loop through a list of bands that I have in a json file (Using Swifty-Json), for some reason when I get down to looping through the names, it returns null.

Json

Small snippet of the JSON

[  
{  
  "Band":{  
     "ID":"1",
     "Name":"The Kooks"
  }
},
{  
  "Band":{  
     "ID":"2",
     "Name":"The Killers"
  }
}
]

Swift Code

 for (_, value) in json {
    for (_,band) in value["Band"] {
       for (_,bandname) in band["Name"] {
           print("Band name: \(bandname)")
       }
     }
 }

The above code returns:

Band name: null

Band name: null

Band name: null

Band name: null

When I try this:

for (_, value) in json {
   for (_,brand) in value["Band"] {
      print(band)
   }
}

I get this result:

The Kooks

1

The Killers

2

Can anyone tell me what the issue is?

1 Answer 1

1

Since the value associated with the key "Name" is a simple string, you want to use:

for (_, value) in json {
    for (_,band) in value["Band"] {
       if let bandname = band["Name"].string {
           print("Band name: \(bandname)")
       } else {
           print("No name specified")
       }
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

On the if let line, I get this error: Initializer for conditional binding must have Optional type, not 'JSON'
Then you should probably mention what you're actually using to parse the JSON itself :)
Is the code above not parsing JSON? I'm sure my question shows that I am looping through and trying to display the Names from the JSON
Never mind, I missed the "swifty-json" part, which is essentially what I'm asking.
oh, ok. I am a little nooby so I was worried I used the wrong terminology. Do, you have any idea with swifty-json what is the problem?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.