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,6182 gold badges20 silver badges40 bronze badges
asked Apr 11, 2011 at 17:32
2
  • 2
    How are you receiving the data? Could you show some Javascript? Commented Apr 11, 2011 at 17:34
  • response.id I think :) Commented Apr 11, 2011 at 17:34

5 Answers 5

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
answered Apr 11, 2011 at 17:34
Sign up to request clarification or add additional context in comments.

1 Comment

Note that this may not work on older browsers. You can use json2.js to get around this.
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/

answered Apr 11, 2011 at 17:33

Comments

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);
answered Apr 11, 2011 at 17:38

Comments

1
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

Comments

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,9852 gold badges27 silver badges37 bronze badges
answered Apr 11, 2011 at 17:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.