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

59 thoughts on “How can I access nested objets in JSON with JS / Ajax request”

Leave a Comment