JSON Parse Error "TypeError: undefined is not an object" "[object Object]

JSON Parse Error "TypeError: undefined is not an object" "[object Object]

我一直在尝试 JSONParse 剩下的 api,但一直没有成功。谁能明白为什么我总是收到 [object Object] 或 undefined 错误?

    <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;

谢谢大家!

  1. 您的 json 字符串无效
  2. 检查您的 data 结构并再次更正循环 (for)
  3. apartment 是一个对象,但你显示它相同 string document.getElementById("friend_1_name").innerHTML = data[0].apartment; 不会工作
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 Formatter & Validator.

你在这里做错了很多事情。 1,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>