WWWIZARDS
WWWIZARDS

Reputation: 159

accessing json data from jquery

I'm creating an ajax app using jQuery 1.4.2 and I've tried using using get(), post() and the ajax() method itself. My php service returns:

[{"k":"label0","v":0.5},{"k":"label1","v":99.43},{"k":"label2","v":2.46},{"k":"label3","v":46.29},{"status":"OK"}]

in my success callback I have tried accessing as json.status and json[0][0] but it always returns "undefined". what am I doing wrong?

function getSysinfo(source) {
    var json = null;
    $.ajax({
        url: source,
        type: 'POST',
        dataType: 'json',
        success: function (data) {
            json = eval("(" + data + ")");
            $('#data').html(json.status);
            alert(json[0][0]);
            refreshChart(json);
        },
        error: function (request, status, error) {
            alert("REQUEST:\t" + request + "\nSTATUS:\t" + status + 
                  "\nERROR:\t" + error);
        }
    });
    return json;
}

I've been googling this for days. How the heck do I access the returned data? any help would be appreciated.

Upvotes: 10

Views: 49810

Answers (8)

Sanjay Shiyal
Sanjay Shiyal

Reputation: 111

$.ajax({
        url: url,
        type: 'POST',
        dataType: 'json',
        data: formData,
        showLoader:true,
        success: function (response) {
            var parsed =  JSON.parse(JSON.stringify(response));
            $.each(parsed, function (key, val) {
                alert( val.name );                      
            });
        },
        error: function (err) {
            alert("Please enter a valid id")    
        }
     });

Upvotes: 1

vitch
vitch

Reputation: 3214

The data parameter is the decoded JSON as you can see in this example:

http://www.jsfiddle.net/rLprV/1/

Upvotes: 1

Dr.Molle
Dr.Molle

Reputation: 117334

nategood already wrote that you don't need do do anything with data, it's already an object.

In this case it's an array, if you like to access the status, you need to retrieve it from the last item of the data-array(that's where you'll find it in this array):

  data[data.length-1].status

But maybe you should think about another structure of your JSON, it doesn't look very comfortable.

Something like that:

{
 "items":[
         {"k":"label0","v":0.5},
         {"k":"label1","v":99.43},
         {"k":"label2","v":2.46},
         {"k":"label3","v":46.29}
        ],
 "status":"OK"
}

...should be easier to handle, because you can simply access data.status instead of first looking where you may find it inside the response(what may be error-prone ).

Upvotes: 2

kobe
kobe

Reputation: 15835

no need to use eval any more use below code which can be more for json

$.getJSON(url+query,function(json){
            $.each(json,function(i,value){

            });
        });

Upvotes: 4

andynormancx
andynormancx

Reputation: 13762

To access that status value you would need:

data[4].status

This is because it is an object stored in the the fifth element in an array, with status being a property on the object.

Upvotes: 15

Marcel Jackwerth
Marcel Jackwerth

Reputation: 54762

Your JSON-data looks like this:

[
    {
        "k": "label0",
        "v": 0.5
    },
    {
        "k": "label1",
        "v": 99.43
    },
    {
        "k": "label2",
        "v": 2.46
    },
    {
        "k": "label3",
        "v": 46.29
    },
    {
        "status": "OK"
    }
]

You would have to read your status using

json[4].status

with the 4 as a magical number or length-1 - not desirable. I would consider modifying your servers response to something more useful like this:

{
    "status": "OK",
    "entries": [ ... ] // add your data here
}

Upvotes: 9

Lorenzo
Lorenzo

Reputation: 29427

In your success callback try:

var parsed = $.parseJSON(data);
$.each(parsed, function (i, jsondata) {
    alert( jsondata.k );
    alert( jsondata.v );
});

Upvotes: 8

nategood
nategood

Reputation: 12005

You don't need the eval("("+data+")");. jQuery is automatically parsing the JSON response for you because you specified dataType:'json'

From the jQuery docs for dataType:

"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)

Upvotes: 5

Related Questions