简体   繁体   中英

How to parse through a JSON object Map

If I have a JSON Object Map :

var dataItem=[{
  "Lucy":{
    "id": 456,
    "full_name": "GOOBER, ANGELA",
    "user_id": "2733245678",
    "stin": "2733212346"
  },
  "Myra":{
    "id": 123,
    "full_name": "BOB, STEVE",
    "user_id": "abc213",
    "stin": "9040923411"
  }
}]

I want to iterate through this list and access the names (ie Lucy, Myra ) and corresponding information

All the loops that I came across looped through the list like this :

var dataItem = [
    {"Name":"Nthal","Class":3,"SubjectName":"English "},
    {"Name":"Mishal","Class":4,"SubjectName":"Grammer"},
    {"Name":"Sanjeev","Class":3,"SubjectName":"Social"},
    {"Name":"Michal","Class":5,"SubjectName":"Gk"},
]

for(x in dataItem)
{
alert(dataItem[x].Name);
alert(dataItem[x].Class);
alert(dataItem[x].SubjectName);
}

Thanks in advance

What you have there is not JSON, maybe because you've already parsed it. You have is an array consisting of a single object, with names for its keys. Regardless, I'll show you how to access that data:

var data = dataItem[0];
for(name in data) {
    alert(name);
    alert(data[name].id);
    alert(data[name].full_name);
}
for (var x in dataItem[0]) {
    if (dataItem[0].hasOwnProperty(x)) {
        console.log(x);
    }
}

http://jsfiddle.net/B44LW/

If you want other properties, then you can use the bracket notation:

dataItem[0][x].id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM