使用空值获取JSON数据

时间:2018-09-26 09:27:45

标签: jquery json

我正在尝试从该URL-https://dog.ceo/api/breeds/list/all中获取数据,该URL具有一些空值。基本上,我试图用狗的品种列表来建立表格。

$.getJSON("https://dog.ceo/api/breeds/list/all", function(data) {
  $.each(data, function(index, d) {
    $('#api-details tbody').append("<tr>" +
      "<td>" + d + "</td>" +
      "</tr>")
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="api-details" class="table">
  <thead class="thead-light">
    <th>List of Breeds</th>
  </thead>
  <tbody>
  </tbody>
</table>

这不返回品种列表,而只是将对象发送到HTML。

2 个答案:

答案 0 :(得分:1)

每个品种都保存在响应中message对象的键中。因此,您需要遍历这些对象,而不是整个data对象。

还要注意,在每个犬种家族中都有一个单独的犬种名称,因此您还需要第二个循环来输出它们。试试这个:

$.getJSON("https://dog.ceo/api/breeds/list/all", function(data) {
  var rows = '';
  Object.keys(data.message).forEach(function(family) {
    rows += '<tr><td>' + family + '</td></tr>';
    
    data.message[family].forEach(function(breed) {
      rows += '<tr><td> - ' + breed + '</td></tr>';
    })
  });
  $('#api-details tbody').append(rows);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="api-details" class="table">
  <thead class="thead-light">
    <th>List of Breeds</th>
  </thead>
  <tbody>
  </tbody>
</table>

答案 1 :(得分:0)

json数据具有两个对象状态和消息,您的数据存储在消息中

因此您需要为each申请data.message

请检查以下代码:

$.getJSON("https://dog.ceo/api/breeds/list/all", function (data) {
    $.each(data.message, function (index, d) {
        if (d != "") {
            $('#api-details tbody').append("<tr>" +
            "<td>" + d + "</td>" +
            "</tr>")
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table id="api-details" class="table">
    <thead class="thead-light">
        <tr><th>List of Breeds</th></tr>
    </thead>
    <tbody></tbody>
</table>

相关问题