Question

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?

Was it helpful?

Solution

[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

OTHER TIPS

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/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top