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,600
  • 2
  • 18
  • 37
slandau
  • 23,528
  • 42
  • 122
  • 184

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
  • 13,775
  • 1
  • 32
  • 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
  • 98,673
  • 67
  • 256
  • 322
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
  • 30,880
  • 8
  • 61
  • 118
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
  • 63,433
  • 20
  • 141
  • 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,785
  • 2
  • 24
  • 37
arun
  • 1