12
{"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.

Nrzonline
  • 1,523
  • 2
  • 18
  • 37
slandau
  • 22,816
  • 40
  • 119
  • 181

5 Answers5

24

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
James Kyburz
  • 12,741
  • 1
  • 31
  • 33
  • 1
    Note that this may not work on older browsers. You can use [json2.js](https://github.com/douglascrockford/JSON-js) to get around this. – lonesomeday Apr 11 '11 at 17:47
4

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/

p.campbell
  • 95,348
  • 63
  • 249
  • 319
2

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);
Community
  • 1
  • 1
amit_g
  • 29,985
  • 8
  • 58
  • 117
1
var results = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}
console.log(results.id)
=>2231f87c-a62c-4c2c-8f5d-b76d11942301

results is now an object.

Mike Lewis
  • 61,841
  • 20
  • 140
  • 111
0

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

alert(response.id);

Otherwise

var str='{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';
Prateek
  • 6,629
  • 2
  • 23
  • 37
arun
  • 1