joda
joda

Reputation: 731

How to use SwiftyJSON to read values from JSON with multiple objects and arrays

I have this JSON, I want to access the values using the SwiftyJSON library:

{"user":[{"id":"33","id_number":"0","first_name":"tom","last_name":"lily","city":"jeddah","gender":"0","DOB":"0000-00-00","phone_namber":"0000000000","email":"000"},
{"id":"34","id_number":"0","first_name":"tom","last_name":"lily","city":"jeddah","gender":"0","DOB":"0000-00-00","phone_namber":"0000000000","email":"000"}]}

This JSON contains arrays and objects. When I try this, it doesn't work:

JSON["lawyers"]["id"].intValue

How can I access the id and other values in this JSON?

Upvotes: 1

Views: 663

Answers (1)

Dan
Dan

Reputation: 303

Firstly, there's no "lawyers" in this JSON, and it'll never start parsing the data. Secondly, all of the values are String types, so if you want to use them as Int, you have to convert them.

So, you have a "user" array, which means that you have to iterate through that array.

After that, you will be able to work with the items in the "user" array and access its values.

Here's a function that I use. Its input is the JSON that I'm working with and it stores it in a dictionary.

var dataArray = [[String: String]]() // Init dictionary

func parseJSON(json: JSON) {
    for item in json["user"].arrayValue { // This is the JSON array which contains the values that you need
        let id = item["id"].stringValue // You access the value here
        let first_name = item["first_name"].stringValue
        let last_name = item["last_name"].stringValue
        let email = item["email"].stringValue

        let obj = ["id": id, "first_name": first_name, "last_name": last_name, "email": email]
        dataArray.append(obj) // This appends the JSON parsed data to an array of dictionaries
    }
}

Usage of this:

func usingTheParsedJSON(){
    for user in dataArray {
        print("user's id: ", user["id"], ", last_name: ", user["last_name"])
        let convertedId: Int = Int(user["id"]) // If you want to use the id as Int. With this dictionary, you can only store it as String, since everything has to have the same type
    }
}

If you can edit the JSON data, then with removing the quotation marks, you can use the numbers as Integers when parsing JSON.

let id = item["id"].intValue // This goes into the func's for loop

Note: to store this in the dictionary, you'll have to convert it to String with String(id). This method for storing data is not the best, I use this because I usually have strings and only one integer.

I hope this solves your problem. Let me know if you need anything else!

PS: there's a typo in the JSON data: phone_namber.

Upvotes: 1

Related Questions