如何访问预先不知道id的json属性

How to access a json attribute which id is not know in advance?

本文关键字:id 不知道 json 属性 何访问 访问      更新时间:2023-09-26

在下面的JSON示例中,当我不知道javascript中那些元素的id时,我如何访问list的项。

{
   "list":{
      "93817":{
         "item_id":"93817"
         "url":"http://url.com",
         "title":"Page Title"
      },
      "935812":{
         "item_id":"935812",
         "url":"http://google.com",
         "title":"Google"
      }
   }
}
var jsonObject = JSON.parse(req.responseText);
var item = jsonObject.list[0] // This does not work

PS:我不能更改JSON的格式,因为它是由第三部分创建的。

如果你的意思是你在编写程序时不知道,但在执行时会知道,你可以使用:

var key = "935812";
console.log(object.list[key]);

如果您的意思是希望查看在执行时存在哪些密钥,您可以对这些密钥进行迭代,如下所示:

for (var key in object.list) {
  if (object.list.hasOwnProperty(key)) {
    console.log(key + ":", object.list[key]);
  }
}

您可以使用"for(i in obj)"Javascript构造来迭代响应。请注意,以这种方式迭代可能会发现原型链中较高对象的属性(谁知道JSON对象经历了什么痛苦…),因此如果您愿意,可以非常明确地进行检查。

response = {
   "list":{
      "93817":{
         "item_id":"93817",
         "url":"http://url.com",
         "title":"Page Title"
      },
      "935812":{
         "item_id":"935812",
         "url":"http://google.com",
         "title":"Google"
      }
   }
};
for (var id in response.list) {
    if (response.list.hasOwnProperty(id)) {
        // Now 'id' is the previously unknown id,
        ​// and response.list[id] is the list items.
        console.log(id, response.list[id]​);
    }
}​
var list = obj["list"];
for (item in list) {
    if (list.hasOwnProperty(item)) {
        alert( list[item].item_id );
    }
}

在这种情况下,hasOwnProperty检查可能没有必要,但通常您可能需要确保它不是继承的属性。

您可以这样循环它们:

for (i in jsonObj.list){ 
    alert(a.list[i].title); 
};