{"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.
5 Answers 5
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
answered Apr 11, 2011 at 17:34
James Kyburz
14.6k1 gold badge34 silver badges33 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
lonesomeday
Note that this may not work on older browsers. You can use json2.js to get around this.
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);
answered Apr 11, 2011 at 17:33
p.campbell
101k71 gold badges265 silver badges326 bronze badges
Comments
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);
answered Apr 11, 2011 at 17:38
amit_g
31.3k8 gold badges67 silver badges125 bronze badges
Comments
var results = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}
console.log(results.id)
=>2231f87c-a62c-4c2c-8f5d-b76d11942301
results is now an object.
answered Apr 11, 2011 at 17:35
Mike Lewis
64.4k20 gold badges144 silver badges111 bronze badges
Comments
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,9852 gold badges27 silver badges37 bronze badges
Comments
lang-js
response.idI think :)