0

How can I parse this array without a key before the square brackets?

[
    {
        "id": 2,
        "model": "RAV 4",
        "brand": "Toyota"
    },
    {
        "id": 1,
        "model": "A6",
        "brand": "Audi"
    }
]

There is a similar question, but for Android.

8
  • The json does have keys, it simply an array of jsons. loop through it and parse it Commented Jun 12, 2016 at 16:11
  • 1
    Arrays are accessed by index, there are two items in the array, at index 0 the dictionary with id = 2 and at index 1 the dictionary with id = 1. Just enumerate the array. Commented Jun 12, 2016 at 16:11
  • 3
    @kye It's an array of dictionaries, not an array of jsons. You do not need to loop and parse. Commented Jun 12, 2016 at 16:14
  • @rmaddy thanks for the correct Commented Jun 12, 2016 at 16:14
  • 1
    @JLT JSON is a textual representation of data. An array is a list. A dictionary is a collection of key-value pairs. As it happens, JSON data is made up of arrays and dictionaries in whatever possible structure is appropriate for the data. The JSON data presented in the question happens to be an array of dictionaries. No one would call it an array of JSON. Commented Jun 12, 2016 at 16:55

2 Answers 2

3

Just parse it using NSJSONSerialization as normal, and cast the result as an array of [String:AnyObject] dictionaries.

So, something like:

if let json = (try? NSJSONSerialization.JSONObjectWithData(yourLoadedNSData, options: NSJSONReadingOptions(rawValue: 0))) as? [[String : AnyObject]] {
    print(json.count) // Should be 2, based on your sample json above
}
Sign up to request clarification or add additional context in comments.

Comments

0

Update for Swift 3

if let json = (try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions(rawValue: 0))) as? [String] {
// do stuff here
}

Just in case of :)

Comments

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.