Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse an array inside parsed JSON in Swift?

Tags:

json

ios

swift

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:

XCode Error

and the code won't compile.

Is this a bug with XCode 6, or am I doing something wrong?

like image 987
plv Avatar asked Jun 03 '14 22:06

plv


People also ask

Can JSON parse parse array?

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.

Can you use arrays in JSON?

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.

What is the use of JSON parse () in JSON explain with example?

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.


1 Answers

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)

like image 57
micahbf Avatar answered Sep 21 '22 14:09

micahbf