Reputation: 989
I'm using an API that returns JSON that looks like this
{
"boards":[
{
"attribute":"value1"
},
{
"attribute":"value2"
},
{
"attribute":"value3",
},
{
"attribute":"value4",
},
{
"attribute":"value5",
},
{
"attribute":"value6",
}
]
}
In Swift I use two functions to get and then parse the JSON
func getJSON(urlToRequest: String) -> NSData{
return NSData(contentsOfURL: NSURL(string: urlToRequest))
}
func parseJSON(inputData: NSData) -> NSDictionary{
var error: NSError?
var boardsDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
return boardsDictionary
}
and then I call it using
var parsedJSON = parseJSON(getJSON("link-to-API"))
The JSON is parsed fine. When I print out
println(parsedJSON["boards"])
I get all the contents of the array. However I am unable to access each individual index. I'm positive it IS an Array, because ween I do
parsedJSON["boards"].count
the correct length is returned. However if I attempt to access the individual indices by using
parsedJSON["boards"][0]
XCode turns off syntax highlighting and gives me this:
and the code won't compile.
Is this a bug with XCode 6, or am I doing something wrong?
Upvotes: 28
Views: 52985
Reputation: 97
You can create a variable
var myBoard: NSArray = parsedJSON["boards"] as! NSArray
and then you can access whatever you have in "boards" like-
println(myBoard[0])
Upvotes: 6
Reputation: 91
Take a look here:https://github.com/lingoer/SwiftyJSON
let json = JSONValue(dataFromNetworking)
if let userName = json[0]["user"]["name"].string{
//Now you got your value
}
Upvotes: 9
Reputation: 1123
The correct way to deal with this would be to check the return from the dictionary key:
if let element = parsedJSON["boards"] {
println(element[0])
}
Upvotes: 4
Reputation: 627
Dictionary access in Swift returns an Optional, so you need to force the value (or use the if let
syntax) to use it.
This works:
parsedJSON["boards"]![0]
(It probably shouldn't crash Xcode, though)
Upvotes: 20