Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery excracting json representations {41: Array[2], 42: Array[1]}

I have the following response from a Ajax call which is this {41: Array[2], 42: Array[1]} Its basically a python dictionary sent back from a server that looks like this: {41: [0:15740, 1:15741], 42: [0:15744]}

So in Jquery I need to be able to get the keys and matching values that are stored within this json representation and be able to display them in an alert. This is the code I have so far but it keeps coming up as data.length: undefined although it does log the data in the line before.

$.ajax({
    url: target,
    dataType: 'json',
    type: 'POST',
    data: JSON.stringify(myData),
    xhrFields: {
        withCredentials: true
    }
})
.done(function(data) {
    console.log('done:', data);
    console.log('data.Length : :', data.length);

    for (var x = 0; x < data.length; x++) {
        spreadsheet = data[x].Id;

        spreadsheet += "<br>";
        spreadsheet += data[x].Name;
        spreadsheet += "<br>";
        console.log('Spreadsheet : ' + spreadsheet)
    }
})
like image 936
whoopididoo Avatar asked Mar 16 '26 14:03

whoopididoo


1 Answers

If the response is JSON, you first need to parse it.

data=JSON.parse(data)

Then you need to iterate over the object like this

for(var key in data) 
{// do stuff here
//you can access the array like this
data[key][0]
//or you can further iterate over the array
for(var x=0; x<data[key].length; x++)
{
//now you can access array element like 
//this
data[key][x]
}
}

Edit: Since the response is not json you don't need the statement.

JSON.parse(data)

for(var key in obj) 
{// do stuff here
var elem;
//or you can further iterate over the array
for(var x=0; x<obj[key].length; x++)
{
//now you can access array element like
//this
console.log(obj[key][x].slice(2));
 elem=obj[key][x].slice(2);//now elem will contain the values 15740,15741
//,15744
}
like image 151
khan Avatar answered Mar 19 '26 04:03

khan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!