Ryan
Ryan

Reputation: 29

Looping through JSON data in javascript not working

I have some JSON data being returned from an AJAX call. I then need to parse this data in javascript.

The data looks like so:

[
 {
 "id": "23",
 "date_created": "2016-05-12 14:52:42"
},
{
 "id": "25",
 "date_created": "2016-05-12 14:52:42"
}
]

Why is it when i run this code on the data that i get multiple undefined's? (var json being the variable holding my json data)

 for(var i = 0; i < json.length; i++) {
     var obj = json[i];

     console.log(obj.id);
  }

However if i assign the json directly to the variable like so:

var json = [
 {
 "id": "23",
 "date_created": "2016-05-12 14:52:42"
},
{
 "id": "25",
 "date_created": "2016-05-12 14:52:42"
}
];

Then it works fine!

Any ideas guys? Thanks

Upvotes: 1

Views: 64

Answers (2)

Deepanshu Gupta
Deepanshu Gupta

Reputation: 240

It is not a JSON that, you are using.

  • It's an object array.
  • When you get JSON, parse that JSON using method JSON.parse.
  • Assign this JSON to a variable and then use iteration over it...

Ex:

 var json ='[{"id": "23","date_created": "2016-05-12 14:52:42"},{"id": "25","date_created": "2016-05-12 14:52:42"}]';
 var parsedJson = JSON.parse(json);
 for(var i = 0; i < parsedJson.length; i++) {
     var obj = parsedJson[i];

     console.log(obj.id);
  }

Upvotes: 0

Prashant G
Prashant G

Reputation: 4900

Make sure the JSON you're getting is not just stringified JSON. In that case do JSON.parse(json_string) and then loop and more processing.

Example:

var string_json = '[{"a":1},{"b":2}]'; // may be your API response is like this
var real_json = JSON.parse(string_json); // real_json contains actual objects
console.log(real_json[0].a, real_json[1].b); // logs 1 2

Upvotes: 1

Related Questions