Looping through array-dictionary-dictionary using SwiftyJSON

1.5k Views Asked by At

I'm trying to loop through this sample of JSON to get age, name and type using SwiftyJSON. I succeeded getting name and age but the type is hard for me. Can someone show me how to do it, please?

"both": [
{
  "id": 130,
  "name": "TMT",
  "age": "2006",
  "created_at": "2016-12-19 21:37:06",
  "updated_at": "2016-12-19 21:37:06",
  "pic": "1482183426.png",
  "pivot": {
    "user_id": 4,
    "car_id": 130,
    "type": "rent"
  }
},
{
  "id": 113,
  "name": "TMT ",
  "age": 2016,
  "created_at": "2016-12-18 14:46:18",
  "updated_at": "2016-12-18 14:47:41",
  "pic": "",
  "pivot": {
    "user_id": 4,
    "car_id": 113,
    "type": "rent"
  }
}
]

work

    let json = JSON(value)
for (key, subJson) in json {

    let cars = subJson["both"]


    for (key, subJson) in cars {

        print(subJson["age"])

}
1

There are 1 best solutions below

0
On BEST ANSWER

All you need to is to access pivot dictionary and read the type key from there.

let json = JSON(value)
for (key, subJson) in json {
    let cars = subJson["both"]
    for (key, subJson) in cars {
        let age = subJson["age"]
        // Access pivot dictionary
        let pivot = subJson["pivot"]
        // Get type from pivot dictionary
        let type = pivot["type"]
    }
}