0

I have been struggling with a few lines of Javascript code which should be straightforward. I have reduced my JSON String to the one found hereafter. The first alert in the code hereafter generates the following message:

{"list":[{"text":"Text1", "created_at":"Date1"},{"text":"Text2", "created_at":"Date2"}]}

However, the second alert generates the following error in IE: Error: Unable to get value of the property '0': object is null or undefined

var data = "{\"list\":[{\"text\":\"Text1\", \"created_at\":\"Date1\"},{\"text\":\"Text2\", \"created_at\":\"Date2\"}]}";
alert(data);
alert(data.list[0].created_at);

Would anyone understand why I am receiving this error?

JF0001
  • 819
  • 7
  • 30

2 Answers2

3

data is an ordinary string; it doesn't have any properties.

You want to parse the JSON in the string into a Javascript object:

var obj = JSON.parse(data);
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Thank you. I was initially parsing the string as you have suggested, but was obtaining another error. Therefore, I had found the following answer at the link hereafter which appeared to suggest the opposite, and thus had removed the parsing altogether. http://stackoverflow.com/questions/14265929/unable-to-solve-error-uncaught-syntaxerror-unexpected-token-o I guess I hadn’t interpreted that answer correctly. I believe that my initial error was related to the format of the JSON Object itself. Thank you again. – JF0001 Sep 22 '13 at 21:18
  • @JF0001: It sounds like you were calling `JSON.parse()` on an object, not a string. – SLaks Sep 22 '13 at 23:00
1

You are using a string with Json formatting, but is not JSON itself.

You should use this:

var data = {"list":[{"text":"Text1", "created_at":"Date1"},{"text":"Text2", "created_at":"Date2"}]};
alert(data.list[0].created_at);

Or use:

var jsonData = JSON.parse(data);
alert(jsonData.list[0].created_at);
Regys
  • 79
  • 1
  • 9