[javascript] Get json value from response

{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}

If I alert the response data I see the above, how do I access the id value?

My controller returns like this:

return Json(
    new {
        id = indicationBase.ID
    }
);

In my ajax success I have this:

success: function(data) {
    var id = data.id.toString();
}

It says data.id is undefined.

This question is related to javascript json

The answer is


If the response is in json then it would be like:

alert(response.id);

Otherwise

var str='{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';

Normally you could access it by its property name:

var foo = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"};
alert(foo.id);

or perhaps you've got a JSON string that needs to be turned into an object:

var foo = jQuery.parseJSON(data);
alert(foo.id);

http://api.jquery.com/jQuery.parseJSON/


Use safely-turning-a-json-string-into-an-object

var jsonString = '{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';

var jsonObject = (new Function("return " + jsonString))();

alert(jsonObject.id);

var results = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}
console.log(results.id)
=>2231f87c-a62c-4c2c-8f5d-b76d11942301

results is now an object.