0

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?

3
  • let json = JSON(value) to let json = JSON(value) as! [String:AnyObject] And try Commented Jul 24, 2017 at 7:37
  • See here for looping through json with SwiftyJson. Commented Jul 24, 2017 at 7:38
  • @MikeAlter crash the entire app. Commented Jul 24, 2017 at 7:41

2 Answers 2

2

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"])
}
Sign up to request clarification or add additional context in comments.

2 Comments

I tried to convert JSON to CLLocationDegrees and it is not possible.
Well, this is not related to How to loop array of JSON object using SwiftyJSON? question. And what do you mean by "it is not possible"?
0

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)")
    }
}

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.