Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 825
slandau Avatar asked Apr 11 '11 17:04

slandau


People also ask

What is response JSON () in fetch?

Response.json()The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON .

What does Response JSON () do python?

json() returns a JSON object of the result (if the result was written in JSON format, if not it raises an error). Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object.


3 Answers

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
like image 64
James Kyburz Avatar answered Oct 18 '22 19:10

James Kyburz


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/

like image 27
p.campbell Avatar answered Oct 18 '22 20:10

p.campbell


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);
like image 2
amit_g Avatar answered Oct 18 '22 19:10

amit_g