Home > Software design >  How to convert Getjson to values in a dictionary or array in Javascript
How to convert Getjson to values in a dictionary or array in Javascript

Time:12-06

I have a Javascript function and get the below values in console if I run the codes:

$(document).ready(function(){
    $.getJSON('http://example.com/json.php',function(urldata){
         console.log(urldata);
    });
})

I get the below in console:

{data: Array(3), draw: 1, recordsTotal: 3, recordsFiltered: 30}
data: Array(3)
0: (6) [1, 'Tokyo', 'Japan', '83', '9', 0]
1: (6) [2, 'Paris', 'France', '16', '8', 0]
2: (6) [3, 'Rome', 'Italy', '44', '6', 0]
length: 3
[[Prototype]]: Array(0)

I tried to put them in an array but I got undefined error message.

var arr = [];
    $(document).ready(function(){
        $.getJSON('http://example.com/json.php',function(urldata){
             for(k in urldata)
            {
               alert("City: "   k[1]   " Country: "   k[2]);
               arr.push(k[1], k[2])
            }
        });
    })

I would like to have the below output in an array or dictionary with easy access to the values:

 --- ------- -------- 
| 1 | Tokyo | Japan  |
 --- ------- -------- 
| 2 | Paris | France |
 --- ------- -------- 
| 3 | Rome  | Italy  |
 --- ------- -------- 

Please, what is wrong with the code?

CodePudding user response:

Based on the structure of the response, try replacing your callback to arr.push(urldata.data)

let arr = [];
    $(document).ready(function(){
        $.getJSON('http://example.com/json.php',function(urldata){
            arr.push(urldata.data)
            // console.log(urldata)
        });
    })

Updated

Based on the provided response on your console.log,

data: Array(3)
0: (6) [1, 'Tokyo', 'Japan', '83', '9', 0]
1: (6) [2, 'Paris', 'France', '16', '8', 0]
2: (6) [3, 'Rome', 'Italy', '44', '6', 0]

You can extract the data by using the following adjustments. Take note that I just used for loop for simplicity and for you to be able to see it, but there are cleaner methods for this.

let arr = [];
$(document).ready(function(){
  $.getJSON('http://example.com/json.php',function(urldata) {
    for (let i=0; i<urldata.data.length; i  ) {
      let formattedData = `City: ${urldata.data[i][1]} Country: ${urldata.data[i][2]}`
    }
  });
})
  • Related