简体   繁体   中英

How can I access nested objets in JSON with JS / Ajax request

I have a nested JSON and want to access the data via ajax request and fill a table in html.

The JSON looks like this:

{
  sum: {
    total: 2,
  },
  data: [
    {
      id: '1',
      attributes: {
        employee: 'B',
        age: 13,
        adress: 'ABCD'
      },
    }, {
      id: '2',
      attributes: {
        employee: 'A',
        age: 12,
        adress: 'ABC'
      },
    }
  ]
};

And im trying to send the request like this:

$(document).ready(function(){
$.getJSON("http://localhost:8000/api/employee", function (data){
    var requested_data = "";
    var i = 0;
    $.each(data, function(key,value){
        requested_data += "<tr>";
        requested_data += "<td>" + value.data[i].attributes.employee + "</td>";
        requested_data += "<td>" + value.data[i].attributes.age + "</td>";
        requested_data += "<td>" + value.data[i].attributes.adress + "</td>";
        requested_data += "</tr>";
        i++;
    $("#requested_table").append(requested_data);
    })
});
});

I always get this error in my console:

Uncaught TypeError: Cannot read property 'attributes' of undefined

You need to use data.data this will return JSON Arrays then access same using key values.

Demo code :

 var data = { sum: { total: 2, }, data: [{ id: '1', attributes: { employee: 'B', age: 13, adress: 'ABCD' }, }, { id: '2', attributes: { employee: 'A', age: 12, adress: 'ABC' }, }] }; $(document).ready(function() { var requested_data = ""; /*$.getJSON("http://localhost:8000/api/employee", function (data){*/ //use here data.data $.each(data.data, function(key, value) { //use directly attributes requested_data += "<tr>"; requested_data += "<td>" + value.attributes.employee + "</td>"; requested_data += "<td>" + value.attributes.age + "</td>"; requested_data += "<td>" + value.attributes.adress + "</td>"; requested_data += "</tr>"; }) $("#requested_table").html(requested_data);//this line should be outside each loop /*})*/ });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="requested_table"> </table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM