2

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

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.