slandau
slandau

Reputation: 24082

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.

Upvotes: 12

Views: 115690

Answers (5)

arun
arun

Reputation: 1

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

alert(response.id);

Otherwise

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

Upvotes: 0

p.campbell
p.campbell

Reputation: 100627

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/

Upvotes: 4

amit_g
amit_g

Reputation: 31270

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);

Upvotes: 2

Mike Lewis
Mike Lewis

Reputation: 64177

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

results is now an object.

Upvotes: 1

James Kyburz
James Kyburz

Reputation: 14503

If response is in json and not a string then

alert(response.id);
or
alert(response['id']);

otherwise

var response = JSON.parse('{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}');
response.id ; //# => 2231f87c-a62c-4c2c-8f5d-b76d11942301

Upvotes: 24

Related Questions