我正在尝试通过键lat
访问JSON文件中的特定值,因为我循环遍历每条记录。但是,当我打印它时,我得到undefined
结果。
JSON
[{"pid":4317129482,"lat":"51.5078","lon":"-0.10467","coords":{"x":-0.10467,"y":51.5078},"points":{"x":-0.10467,"y":51.5078}},
{"pid":4356791546,"lat":"51.522","lon":"-0.101773","coords":{"x":-0.101773,"y":51.522},"points":{"x":-0.101773,"y":51.522}},
JSON存储在data
代码尝试
$.each(data, function(key, value){
if (key == "lat") {
console.log(value)
}
OR
$.each(data, function(item){
console.log(item.lat)
}
答案 0 :(得分:1)
如果你发布的JSON是正确的,那么它就是一个对象数组。所以$.each(data,function(key,val){})
将返回索引,对象即key为0,1,2并对该对象赋值。
访问
" LAT":" 51.522"
你必须这样做
$.each(data,function(key,val){
//val here is your object. For each object in the array you have to loop again
$.each(val,function(k,v){
//now since val is an object looping through it will return your key-value pairs
if(k == 'lat'){
//Do something
}
})
})
答案 1 :(得分:0)
试试这个
$.each(data, function(key, value){
console.log(value.lat);
});
答案 2 :(得分:0)
如果它有助于更改参数名称更多地表明您使用$.each
对于像:
这样的数组$.each(arr, function(index, arrayElement){
})
对象
$.each(obj, function(objKey, propertyValue){
});
当不确定循环中的内容使用console.log([index, arrayElement])
时,您可以在浏览器开发工具控制台中检查它