Get json value from response

106,863

Solution 1

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

Solution 2

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/

Solution 3

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);

Solution 4

var results = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}
console.log(results.id)
=>2231f87c-a62c-4c2c-8f5d-b76d11942301

results is now an object.

Share:
106,863

Related videos on Youtube

slandau
Author by

slandau

Updated on June 01, 2020

Comments

  • slandau
    slandau almost 4 years
    {"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.

    • lonesomeday
      lonesomeday about 13 years
      How are you receiving the data? Could you show some Javascript?
  • lonesomeday
    lonesomeday about 13 years
    Note that this may not work on older browsers. You can use json2.js to get around this.

Related