Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through/Parsing JSON Object via JavaScript

I'm having a problem with jQuery/Ajax/JSON. I'm using a jQuery ajax post like so...

$.ajax({
  type: "POST",
  dataType: "json",
  url: "someurl.com",
  data: "cmd="+escape(me.cmd)+"&q="+q+"&"+me.args,
  success: function(objJSON){
    blah blah...
  }
});

It's my understanding that this will return a JavaScript JSON object? The text that the ajax post produces is this (I believe this is valid JSON)...

{
  "student":{
    "id": 456,
    "full_name": "GOOBER, ANGELA",
    "user_id": "2733245678",
    "stin": "2733212346"
  },
  "student":{
    "id": 123,
    "full_name": "BOB, STEVE",
    "user_id": "abc213",
    "stin": "9040923411"
  }
}

I can't seem to figure out how to parse through the JSON object returned by the jQuery ajax post... basically I want to loop through and make a div out of each student returned like so...

$("<div id=\"" + student.id + "\">" + student.full_name + " (" + student.user_id + " - " + student.stin + ")</div>")

I just can't seem to figure out how to do it...

Thanks!

like image 836
Ryan Avatar asked Oct 28 '09 13:10

Ryan


2 Answers

The JSON you have currently will not work because the second "student" effectively replaces the first, since these are just properties in an object.

If you can control the JSON output, change it to:

{
  "student":[{
    "id": 456,
    "full_name": "GOOBER, ANGELA",
    "user_id": "2733245678",
    "stin": "2733212346"
    },{
    "id": 123,
    "full_name": "BOB, STEVE",
    "user_id": "abc213",
    "stin": "9040923411"
  }]
}

Then you have an an array which you can loop over:

for(var i=0; i<objJSON.student.length; i++) {
  ...objJSON.student[i]...
  }
like image 171
jwl Avatar answered Oct 18 '22 22:10

jwl


Your JSON object is incorrect because it has multiple properties with the same name. You should be returning an array of "student" objects.

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

Then you can iterate over it as so:

 for (var i = 0, len = objJSON.length; i < len; ++i) {
     var student = objJSON[i];
     $("<div id=\"" + student.id + "\">" + student.full_name + " (" + student.user_id + " - " + student.stin + ")</div>")...
 }
like image 28
tvanfosson Avatar answered Oct 19 '22 00:10

tvanfosson