如何使用 JS / Ajax 请求访问 JSON 中的嵌套对象

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

我有一个嵌套的 JSON,想通过 ajax 请求访问数据,并在 html 中填写 table。

JSON 看起来像这样:

{
  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(){
$.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);
    })
});
});

我的控制台总是出现这个错误:

Uncaught TypeError: Cannot read property 'attributes' of undefined

您需要使用 data.data 这将 return JSON 数组 然后使用键值访问它们。

演示代码 :

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>