javascriptjsoncappuccino

JSON.parse not evaluating JSON strings properly


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?


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