我目前正在学习JSON并且无法获得嵌套数据 我想得到“id”和“city”。
这是我的代码:
var url = "jsonURL";
$.getJSON (url, function(b) {
for (var i = 0; i < b.friends.data.length; i++) {
var data = b.friends.data[i];
if (data.id == undefined) {
html+= "<td id='id'> - </td>";
}
else {
html+= "<td id='id'>" + data.id + "</td>";
}
if (data.location.location.city == undefined) {
html+= "<td id='city'> - </td>";
}
else {
html+= "<td id='city'>" + data.location.location.city + "</td>";
}
}
}
JSON看起来像这样。
{ "friends": { "data": [ { "id": "friend1", "location": { "location": { "city": "Tangerang", "country": "Indonesia" }, "id": "1" } }, { "id": "friend2", "location": { "location": { "city": "Makassar", "country": "Indonesia" }, "id": "2" } } ], }, "id": "myID" }
问题:“id”的总数据约为600 如果我不试图获得“城市”,循环似乎很好 如果我做,则“id”的循环仅显示4个数据 结果是
“未捕获的TypeError:无法读取未定义的属性'位置”
我把它改成了
data.location == undefined || data.location.location == undefined || data.location.location.city == undefined
答案 0 :(得分:0)
未捕获的TypeError:无法读取未定义的属性“位置”
未捕获意味着错误未在catch语句中捕获,collect2: error: ld returned 1 exit status
apps/visualisation/CMakeFiles/opencv_visualisation.dir/build.make:104: recipe for target 'bin/opencv_visualisation' failed
make[2]: *** [bin/opencv_visualisation] Error 1
CMakeFiles/Makefile2:7461: recipe for target 'apps/visualisation/CMakeFiles/opencv_visualisation.dir/all' failed
make[1]: *** [apps/visualisation/CMakeFiles/opencv_visualisation.dir/all] Error 2
Makefile:149: recipe for target 'all' failed
make: *** [all] Error 2
是错误的名称。
好像您正在尝试访问未定义对象的属性“位置”。在执行TypeError
语句之前测试data.location
是否已定义以获取if
。
始终有效:
city