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?
parse method to parse a JSON array into its JavaScript equivalent. The only parameter we passed to the method is the JSON string that should be parsed. If you provide invalid JSON to the method, a SyntaxError exception is thrown.
Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.
The JSON. parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With