uhfocuz
uhfocuz

Reputation: 3180

Accessing JSON data in swift

I am trying to access JSON data in my swift code and I'm having trouble getting it to return correctly. Here is my JSON code:

    [
    {
        "id": "1",
        "isImage": "0",
        "name": "test name",
        "post": "test post",
        "time": "10:27",
        "ip": "192.168.1.1",
        "city ": "Columbus",
        "latlong": "39.896418,-82.9751105",
        "clientID": "clientID",
        "popularity": "300"
    },
    {
        "id": "2",
        "isImage": "0",
        "name": "test name two",
        "post": "test post two",
        "time": "13:37",
        "ip": "192.168.1.1",
        "city ": "Columbus",
        "latlong": "39.896418,-82.9751105",
        "clientID": "clientID",
        "popularity": "69"
    }
    ]

I'd just like to know how to access the data by their keys json[0].['id'] or? I am currently using this json.swift module and trying to access the data with

func jsonHandle(data: NSString) {
            var parsedJSON = JSON(data)
            var id = parsedJSON[0].["id"]
            NSLog("\(id)")
    }

but it returns nothing. Any Ideas?

Upvotes: 2

Views: 1342

Answers (1)

Rob
Rob

Reputation: 437372

You can call the JSON(string:...) rendition and eliminate the period between the [0] and the ["id"]:

func jsonHandle(data: NSString) {
    let parsedJSON = JSON(string: data)
    var id = parsedJSON[0]["id"]
    NSLog("\(id)")
}

Or, if you had a NSData you could use the JSON(data: ...) rendition:

func jsonHandle(data: NSData) {
    let parsedJSON = JSON(data: data)
    let id = parsedJSON[0]["id"]
    NSLog("\(id)")
}

Or, if you wanted to use the native NSJSONSerialization, rather than that third-party library, you could:

func jsonHandle(data: NSData) {
    var error: NSError?
    let parsedJSON = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as NSArray
    let id = parsedJSON[0]["id"]
    NSLog("\(id)")
}

Personally, I'd lean towards the standard NSJSONSerialization approach as it's a tried and true approach, but that's your call.

Upvotes: 2

Related Questions