从API中的对象获取数据

时间:2020-09-13 14:43:46

标签: javascript jquery api

function fetch(){
    $.get("https://api.covid19india.org/state_district_wise.json", function(data){
        console.log(data);
    })
}

我想用上述api中的api数据创建一个表。数据看起来像这样:

{
  "State Unassigned": {
    "districtData": {
      "Unassigned": {
        "notes": "",
        "active": 0,
        "confirmed": 0,
        "deceased": 0,
        "recovered": 0,
        "delta": {
          "confirmed": 0,
          "deceased": 0,
          "recovered": 0
        }
      }
    },
    "statecode": "UN"
  },
  "Andaman and Nicobar Islands": {
    "districtData": {
      "Nicobars": {
        "notes": "District-wise numbers are out-dated as cumulative counts for each district are not reported in bulletin",
        "active": 0,
        "confirmed": 0,
        "deceased": 0,
        "recovered": 0,
        "delta": {
          "confirmed": 0,
          "deceased": 0,
          "recovered": 0
        }
      },
      "North and Middle Andaman": {
        "notes": "District-wise numbers are out-dated as cumulative counts for each district are not reported in bulletin",
        "active": 0,
        "confirmed": 1,
        "deceased": 0,
        "recovered": 1,
        "delta": {
          "confirmed": 0,
          "deceased": 0,
          "recovered": 0
        }
      }
    }
  }
}

我想知道如何为所有此类对象获取数据。您还可以从提到的API中查看代码。我想为所有对象确认,已故和已恢复案件。 我想要具有地区,已确认,已故和已恢复案件的表作为列。我知道如何将数据加到表中。我唯一不知道的是如何获取那里存在的所有对象的数据。

1 个答案:

答案 0 :(得分:1)

如果我理解您的问题,那么您正在寻找使用从此Web服务获取的数据填充HTML表的方法。当您用jquery标记问题时,我想您想使用它。

这是您可以执行的操作:

function populateTable($table) {
    $table.empty().append($("<tr>").append(
        $("<th>").text("state"),
        $("<th>").text("statecode"),
        $("<th>").text("district"),
        $("<th>").text("active"),
        $("<th>").text("confirmed"),
        $("<th>").text("deceased"),
        $("<th>").text("recovered")
    ));
    
    let url = "https://api.covid19india.org/state_district_wise.json";
    $.getJSON(url).then(function (data) {
        for (let state in data) {
            let {statecode, districtData} = data[state]
            for (let district in districtData) {
                let { active, confirmed, deceased, recovered } = districtData[district];
                $table.append($("<tr>").append(
                    $("<td>").text(state),
                    $("<td>").text(statecode),
                    $("<td>").text(district),
                    $("<td>").text(active),
                    $("<td>").text(confirmed),
                    $("<td>").text(deceased),
                    $("<td>").text(recovered)
                ));
            }
        }
    });
}

populateTable($("#table"));
table { border-collapse: collapse; border: 1px solid }
td, th { border: 1px solid }
td:nth-child(4),
td:nth-child(5),
td:nth-child(6),
td:nth-child(7) { text-align: right }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<table id="table"></table>