JSON 解析错误“TypeError:undefined 不是对象”[object Object]
2021-03-15
1852
我一直在尝试 JSONParse 这个 rest api,但没有任何结果。有人能明白为什么我不断收到 [object Object] 或未定义错误吗?
<div id="store_1_name"></div>
<div id="owner_1_name"></div>
<div id="friend_1_name"></div>
var raw_data_string = '{"2":[{"buy":[{"house":"loan","condo":{"USD":64311.9005450},"apartment":{}},{"house":"rent","condo":{"USD":2015.38570},"apartment":{}}]}';
var data = JSON.parse(raw_data_string);
for (var i in data) {
ParseUpdate(data[i].house, data[i].condo, data[i].apartment);
}
function ParseUpdate(house, condo, aparment) {
var house = data[i].house;
var condo = data[i].condo;
var apartment = data[i].buy.apartment;
}
document.getElementById("store_1_name").innerHTML = data[0].house;
document.getElementById("owner_1_name").innerHTML = data[0].condo;
document.getElementById("friend_1_name").innerHTML = data[0].apartment;
谢谢大家!
3个回答
您在这里做错了很多事情。第一,JSON 字符串无效。第二,您尝试在
for
循环中访问错误的元素。第三,如果您还在同一个循环中访问
data[i].house
,则
data[i].buy.apartment
不存在,因为它们位于同一个对象
buy
内。第四,您尝试在 div 的
innerHTML
中显示 JSON 对象,您应该在其中访问要显示的字符串值或
stringify
整个对象。
var raw_data_string = '{"2":[{"buy":[{"house":"loan","condo":{"USD":64311.9005450},"apartment":{}},{"house":"rent","condo":{"USD":2015.38570},"apartment":{}}]}]}';
var data = JSON.parse(raw_data_string)[2][0]['buy'];
for (var i in data) {
ParseUpdate(data[i].house, data[i].condo, data[i].apartment);
}
function ParseUpdate(house, condo, aparment) {
var house = data[i].house;
var condo = data[i].condo;
var apartment = data[i].apartment;
}
document.getElementById("store_1_name").innerHTML = data[0].house;
document.getElementById("owner_1_name").innerHTML = JSON.stringify(data[0].condo);
document.getElementById("friend_1_name").innerHTML = JSON.stringify(data[0].apartment);
<div id="store_1_name"></div>
<div id="owner_1_name"></div>
<div id="friend_1_name"></div>
Rifat Bin Reza
2021-03-15
- 您的 json 字符串无效
-
检查您的
data
结构并再次更正循环 (for
) -
apartment
是一个对象,但您向它显示相同的string
document.getElementById("friend_1_name").innerHTML = data[0].apartment;
不起作用
BMW.dev19
2021-03-15
var raw_data_string =
'{"2":[{"buy":[{"house":"loan","condo":{"USD":64311.9005450},"apartment":{}},{"house":"rent","condo":{"USD":2015.38570},"apartment":{}}]}]}';
var data = JSON.parse(raw_data_string);
console.log(data);
raw_data_string 中缺少一些右括号。我建议使用 JSON 格式化程序和验证程序 。
Chhiring
2021-03-15