user2816983
user2816983

Reputation:

Get parameter from JSON

In data from server I get the following JSON:

{
    "response": {
        "upload_url": "http:\/\/cs9458.vk.com\/upload.php?act=do_add&mid=6299927&aid=-14&gid=0&hash=73e525a1e2f4e6a0f5fb4c171d0fa3e5&rhash=bb38f2754c32af9252326317491a2c31&swfupload=1&api=1&wallphoto=1",
        "aid": -14,
        "mid": 6299927
    }
}

I need to get upload_url. I'm doing:

function (data) {
    var arrg = JSON.parse(data);
    alert(data.upload_url);
});

but it doesn't work (alert doesn't show).

How do I get parameter upload_url?

Upvotes: 5

Views: 24160

Answers (4)

Daniel
Daniel

Reputation: 4946

There are several correct answers here, but there is one trigger that decides how you should handle your returned data.

When you use an ajax request and use JSON data format, you can handle the data in two ways.

  1. treat your data as JSON when it returns
  2. configure your ajax call for JSON by adding a dataType

See the following examples:

returned data string:

{"color1":"green","color2":"red","color3":"blue"}

ajax call without dataType:

$.ajax({
    method: "post",
    url: "ajax.php",
    data: data,
    success: function (response) {
        var data = JSON.parse(response);
        console.log(data.color1); // renders green
        // do stuff 

    }
});

ajax call with dataType:

$.ajax({
    method: "post",
    url: "ajax.php",
    dataType: "json", // added dataType
    data: data,
    success: function (response) {
        console.log(response.color1); // renders green
        // do stuff 
    }
});

In your case you probably used JSON.parse() when the call was already configured for JSON. Hope this makes things clear.

Upvotes: 2

Samuel  Arroyo
Samuel Arroyo

Reputation: 19

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

Upvotes: 1

Joe Simmons
Joe Simmons

Reputation: 1848

It looks like you need to access arrg, not data. Also you need to access the 'response' key first.

function (data) {
    var arrg = JSON.parse(data);
    alert( arrg.response.upload_url);
}

Upvotes: 6

Chris Montgomery
Chris Montgomery

Reputation: 2354

Your code has a small error. try:

function (data) {
   var arrg = JSON.parse(data);
   alert(arrg.response.upload_url);
});

Upvotes: 0

Related Questions