3

In the following JSON example, how can I access item of list when I do not know the id of those elements in javascript.

{
   "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: I can not change the format of the JSON since it is created by a third part.

Phong
  • 6,600
  • 4
  • 32
  • 61

4 Answers4

4

If you mean you don't know it at the time you write the program, but will at execution time, you can use:

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

If you mean that you want to see which keys are present at execution time, you can iterate over the keys like this:

for (var key in object.list) {
  if (object.list.hasOwnProperty(key)) {
    console.log(key + ":", object.list[key]);
  }
}
Amadan
  • 191,408
  • 23
  • 240
  • 301
3

You can iterate over the response using the "for (i in obj)" Javascript construct. Beware that iterating in this manner may uncover properties from higher objects in the prototype chain (who knows what wringer your JSON object went through...), so you can be very explicit if you want, and check for that.

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]​);
    }
}​
Jason Bury
  • 328
  • 1
  • 4
1
var list = obj["list"];
for (item in list) {
    if (list.hasOwnProperty(item)) {
        alert( list[item].item_id );
    }
}

The hasOwnProperty check is probably not necessary in this case, but in general you might want to make sure that it isn't an inherited property.

tvanfosson
  • 524,688
  • 99
  • 697
  • 795
1

You cal loop through them like this:

for (i in jsonObj.list){ 
    alert(a.list[i].title); 
};
Lycha
  • 9,937
  • 3
  • 38
  • 43