JSON.parse not evaluating JSON strings properly

4.7k Views Asked by At

I am using JSON.parse to parse this JSON string

[{"created_at":"2012-01-24T22:36:21Z","name":"joe","age":42,"updated_at":"2012-01-24T22:36:21Z"}]

However I am simply getting this result as the output:

[object Object]

Which shouldn't be the result. I am using this within the Cappuccino framework. Does anyone know what I am doing wrong here?

3

There are 3 best solutions below

1
Adam Rackis On BEST ANSWER

[object Object] is what objects display when you call toString on them. It looks like you're taking your result and trying to call obj.toString()

Also, your JSON is an array with one element in it, so to verify that your result is correct, you can access the name property on the [0] index:

obj[0].name // should be "joe".

var text = '[{"created_at":"2012-01-24T22:36:21Z","name":"joe","age":42,"updated_at":"2012-01-24T22:36:21Z"}]';

var obj = JSON.parse(text);

alert(obj[0].name); //alerts joe

DEMO


Or get rid of the array, since it's not really doing much

var text = '{"created_at":"2012-01-24T22:36:21Z","name":"joe","age":42,"updated_at":"2012-01-24T22:36:21Z"}';

var obj = JSON.parse(text);

alert(obj.name); //still joe

DEMO

3
Eric Hodonsky On

This is an array because it's in square brackets - [] - remove these and it should work... Even though this is 'syntactically' correct the parser sees this as an array (which is a type of object) but won't do the work on it the way you'd expect.

Also for future reference: Try to lint it, and see if your syntax is messed up: http://jsonlint.com/

0
TecHalo On

This is an old subject, but nonetheless, I spent hours trying to figure out what was going on. So, hopefully this will help someone else in the future.

My issue was setting up a simple ajax call, and doing something with the resultset from said ajax call. However, no matter what I did, I couldn't get the json resultset to an object.

I ended up stepping through everything in the debugger window and noticed old code that was no longer active was showing up on the sidebar (dom detail). So, my data had been cached. I cleared the cache, and boom! Everything worked.