[英]How to loop array of JSON object using SwiftyJSON?
I want to loop an array of JSON objects but it keeps giving me error 我想循环一个JSON对象数组,但它一直给我错误
[
{
"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 如果我
print item
以查看值,我将得到
("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? 我该怎么做才能解决这个问题?
Your keys
are of type String
. 您的
keys
类型为String
。 Here your keys are "0"
, "1"
etc. 这里的键是
"0"
, "1"
等。
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: 编辑:如果您不想使用
index
,则可以使用_
替换index
例如:
for(_, subJson): (String, JSON) in json {
print(subJson["latitude"])
}
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)")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.