1

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

6
  • 1
    Where is json getting a value from? Commented May 13, 2016 at 6:57
  • Where do you declare json? How do you assign var json the returned json data? Commented May 13, 2016 at 6:58
  • 1
    Make sure the JSON you're getting is not stringified JSON. In that case do JSON.parse(json_string) and then loop and more ... Commented May 13, 2016 at 6:58
  • Spot on Prashant! Thanks guy! Commented May 13, 2016 at 7:00
  • json isn't being set correctly. Chrome offers some pretty legit tools for debugging. Set a breakpoint in the Sources tab of the dev tools and see what the actual value is at runtime. Commented May 13, 2016 at 7:01

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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);
  }

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.