0

I'm trying to loop through some JSON that has some nested data. The JSON structure is such:

var data =[
{"otherdata":"tons of other data",
 "studentlist":{
             "user":{
                     "first":"john",
                     "last":"doe",
                     "status":"good", 
                     "id":"100404"
              }, 
            "user":{
                   "first":"jane",
                   "last":"doe",
                   "status":"bad", 
                   "id":"100405"
             }
}];

I'm trying to loop through "data", but more importantly, I need to loop through each user. However using jquery's .each(), but it either fails or shows an error for .length. When I'm tracing out in my console.

var student = data.studentlist;
$.each(student, function(i, item){
   console.log('student: ' + student.user[i].id);
});
1
  • you're not looping through json. json is a text-encoding of a javascript data structure. you're looping through a javascript structure, and it's a JS structure like any other. just because it used to be json is irrelevant. consider JS the wrapping paper your christmas present came in. Commented Sep 10, 2015 at 18:14

4 Answers 4

1

You have your data in an array or objects you need to access it like so:

data[0].studentlist

Or just remove [] from around the data then you can access it like this:

data.studentlist

Also there are other problems with your data structure i.e. you cannot have 2 "user" keys you would need to make that an array objects. This is what I believe you want your structure to look like:

var data = {
"otherdata":"tons of other data",
    "studentlist":{
         "user":[
                 {
                    "first":"john",
                    "last":"doe",
                    "status":"good", 
                    "id":"100404"
                 }, 
                 {
                    "first":"jane",
                    "last":"doe",
                    "status":"bad", 
                    "id":"100405"
                 }
                ]
    }
};
Sign up to request clarification or add additional context in comments.

Comments

0

Loop through each user:

var length = data[0].studentlist.length;
for(i=0; i<length; i++)
   data[0].studentlist[i];
});

Comments

0

Here is how I would do it:

for (var i in data[0].studentlist){
  var user = data[0].studentlist[i];
  console.log('student: ' + user.id);
}

Comments

0

Using your code, it should work like this:

var student = data[0].studentlist;
$.each(student, function(i, item){
  console.log('student: ' + item);
});

You might recheck the jquery-each documentation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.