如何使用SwiftyJSON循环JSON对象的数组?

时间:2017-07-24 07:31:15

标签: ios swift

我想循环一个JSON对象数组,但它一直给我错误

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

代码示例

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

如果我print item看到该值,我会得到

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

我该怎么做才能解决这个问题?

2 个答案:

答案 0 :(得分:2)

您的keys类型为String。您的密钥为"0""1"等。

试试这个:

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

修改:如果您不想使用index进行任何操作,只需使用index替换_即可:

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

答案 1 :(得分:0)

试试这段代码

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