固定 - (javascript)无法解析嵌套的JSON数据
问题描述:
我目前正在学习JSON并被卡住以获取嵌套数据。
我想获得“id”和“city”。
固定 - (javascript)无法解析嵌套的JSON数据
这里是我的代码:
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个数据。
结果是
"Uncaught TypeError: Cannot read property 'location' of undefined"
。什么可能是错的?
UPDATE
=========================
固定。我把它变成data.location == undefined || data.location.location == undefined || data.location.location.city == undefined
答
Uncaught TypeError: Cannot read property 'location' of undefined
未捕获意味着错误的catch语句中没有抓住,TypeError
是错误的名字。
好像你正试图访问未定义对象的属性'位置'。测试data.location
是在执行if
语句以获取city
之前定义的。
它始终工作:
try{
if (data.location.location.city == undefined) {
html+= "<td id='city'> - </td>";
} else {
html+= "<td id='city'>" + data.location.location.city + "</td>";
}
}catch(e){
if(e){
// If fails, Do something else
}
}
还有你的工作对我来说所显示的数据处理代码:https://jsfiddle.net/d2mL7stp/。 (顺便说一句,函数中的代码并不涉及JSON:'$ .getJSON()'方法解析JSON以创建(嵌套)对象,并将该对象传递给函数中的'b'参数。) – nnnnnn
当总数据大约是600时,循环仅显示4个数据。当我删除“城市”时,一切都正常。 – Igniel
那么你是说,不工作的部分是在JSON *而不是*在问题中显示? – nnnnnn