nickjf89 nickjf89 - 6 months ago 48
Swift Question

Parsing JSON response in Swift 3

I've got an API endpoint that returns JSON in the following format:

"id": "1",
"name": "John"
"id": "2",
"name": "Jane"
"id": "3",
"name": "Nick"

I am trying to parse this in Swift 3, but I can only find examples to parse JSON formatted like so:

"blogs": [
"needspassword": true,
"id": 73,
"url": "",
"name": "Bloxus test"
"needspassword": false,
"id": 74,
"url": "",
"name": "Manila Test"
"stat": "ok"

, which has an extra level above what mine does.

So, where examples I've seen are simply parsing their data like
, I can't do that as my format is different.

How can I parse the format I've got, or how can I return a format that is easier to parse?

Any suggestions appreciated, thanks!


This will parse it when placed in the network call.

        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions()) as! [[String : AnyObject]]
            let firstPerson = json[0]
            let id = firstPerson["id"] as! String
            let name = firstPerson["name"] as! String
        } catch {
            //handle error

Also, I tend to be against advising third party libraries, but SwiftyJSON is an exception I make. If you want to try it, add this to your pod file:

pod SwiftyJSON', '3.0.0'