使用javascript循环访问JSON

时间:2015-08-18 13:53:33

标签: javascript json

以下是如何迭代javascript对象的许多示例。这对我来说真的很好

    var text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';

obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;

但是没有弄清楚如何迭代obj中的值。像这样试过

    for(var k in obj) {
    if (obj.hasOwnProperty(k)) {
        if (obj.hasOwnProperty(k)) {
             out +=("Key is " + k + ", value is" + obj[k].firstName);
        }
    }
}

但失败了。你可以看到从例子中偷走了。如果有人可以帮助一些javascript代码迭代JSON键值对?

3 个答案:

答案 0 :(得分:2)

解析后,obj变量引用具有employees属性的对象,该属性引用数组。所以:

obj.employees.forEach(function(employee) {
    // ...
});

var i, employee;
for (i = 0; i < obj.employees.length; ++i) {
    employee = obj.employees[i];
    // ...
}

...或this answer中概述的其他几种方式。

答案 1 :(得分:1)

您的示例json具有父键员工,其具有子对象数组。 然后你必须循环遍历数组,如果你知道键,你可以使用Object.keys,它将以数组格式返回对象中的键列表。

&#13;
&#13;
var text = '{"employees":[' +
  '{"firstName":"John","lastName":"Doe" },' +
  '{"firstName":"Anna","lastName":"Smith" },' +
  '{"firstName":"Peter","lastName":"Jones" }]}';

obj = JSON.parse(text);

Object.keys(obj).forEach(function(k) { //Loop through keys of obj.
  obj[k].forEach(function(elm) {  //Loop through all elements of first object array
    console.log(elm.firstName+"_"+elm.lastName)
  })
})
&#13;
&#13;
&#13;

答案 2 :(得分:0)

当您尝试访问不存在的obj["employees"].firstName时,它无效。

for(var k in obj) {
  if (obj.hasOwnProperty(k)){
    var employee = obj[k];
    for(var i in employee){
      out +="Key is " + i + ", value is" + employee[i].firstName;
    }
  }
}

OR

var employee = obj["employees"];
for(var i in employee){
  out +="Key is " + i + ", value is" + employee[i].firstName;
}