Jquery highlighting json views {41: array [2], 42: array [1]}

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

So, in JQuery, I need to get the keys and corresponding values ​​that are stored in this json view and be able to display them in the post. This is the code I have so far, but it keeps showing up as data.length: undefined even though it logs the data in the string 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)
    }
})

      

+3


source to share


4 answers


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

data=JSON.parse(data)

      

Then you need to iterate over an 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 an instruction.

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
}

      

+1


source


Here data can be objects. Try using for - c. for (var x in data) set for a for loop. This might solve your problem.



 for (var x in data) {
        spreadsheet = data[x].Id;

        spreadsheet += "<br>";
        spreadsheet += data[x].Name;
        spreadsheet += "<br>";
        console.log('Spreadsheet : ' + spreadsheet)
    }

      

0


source


You can try this:

var obj = data;

jQuery.each(Object.keys(obj), function(i, x){
  spreadsheet = data[x].Id;

  spreadsheet += "<br>";
  spreadsheet += data[x].Name;
  spreadsheet += "<br>";
})

      

0


source


convert to Json format if the resulting "data" value is a string

var jsonData= JSON.parse(data) //if 'data' is string type.

      

Please share a data type or some approximate piece of data you are getting.

0


source







All Articles