sinusGob
sinusGob

Reputation: 4313

How to loop array of JSON object using SwiftyJSON?

I want to loop an array of JSON objects but it keeps giving me error

[
  {
    "key" : "501",
    "latitude" : 3.0691697,
    "longitude" : 333.64444639369011,
    "distance" : 5,
  },
  {
    "key" : "502",
    "latitude" : 3.073096722364426,
    "longitude" :12.4444000,
    "distance" : 487,
  }
]

The code example

if let value = response.result.value {
   let json = JSON(value)

  // This is the part Where I got stuck                  
   for item in json {

       print (item["latitude"]) // Keep giving me "Latitude is not a subscript of JSON"
    }
}

If I print item to see the value, I will get

("0", {
  "latitude" : 3.0691697,
  "longitude" : 333.64444639369011,
  "key" : "501",
  "distance" : 5
})
("1", {
  "latitude" : 3.073096722364426,
  "longitude" : 12.4444000,
  "key" : "502",
  "distance" : 487
})

What should I do to solve this problem?

Upvotes: 0

Views: 827

Answers (2)

nayem
nayem

Reputation: 7595

Your keys are of type String. Here your keys are "0", "1" etc.

Try this:

for (index,subJson):(String, JSON) in json {
    //Do something you want
    print (subJson["latitude"])
}

Edit: If you don't want to use index for anything, you can just replace index using a _ like:

for(_, subJson): (String, JSON) in json {
        print(subJson["latitude"])
}

Upvotes: 2

ddb
ddb

Reputation: 2435

try this piece of code

for (key0,json) in response.result.value as! Dictionary<String, AnyObject> 
{
    print("key0 \(key0), json \(json)")
    for (key,val) in json as! Dictionary<String, AnyObject>
    {
        print("key \(key), val \(val)")
    }
}

Upvotes: 0

Related Questions