我如何返回 JSON 响应的特定部分?

问题描述

我第一次在 JavaScript 中使用 JSON 和 API 调用 - 特别是使用 What3Words 转换为坐标 API。

我了解基本教程,即使用 3 个词搜索使用以下代码将位置作为对象返回:

what3words.api.convertToCoordinates("shield.mats.windy").then(function (response) {
            console.log("[convertToCoordinates]",response);
        });

返回的 JSON 如下所示:

{
"country": "GB","square": {
    "southwest": {
        "lng": -0.119971,"lat": 51.517491
    },"northeast": {
        "lng": -0.119927,"lat": 51.517518
    }
},"nearestPlace": "Clerkenwell,London","coordinates": {
    "lng": -0.119949,"lat": 51.517505
},"words": "shield.mats.windy","language": "en","map": "https://w3w.co/shield.mats.windy"
}

然后,例如,我如何以编程方式解析坐标对象以作为字符串返回并显示在 HTML 文件上?

解决方法

json 不是字符串,因此您无需解析它即可检索数据。您可以直接访问您需要的字段:例如,const sprite = document.querySelector(".charsprite"); document.addEventListener("keydown",moveChar); function moveChar(e) { switch (e.keyCode) { case 37: if (!sprite.classList.contains("faceup")) sprite.classList.add("faceup"); break; } } 将返回 -0.119949

,

一旦您将 JSON 字符串解析为 object,请使用以下内容:

const myData = JSON.parse(myJSON);

您将能够编写指向该对象不同部分的指针。

例如

  • myData.square.northeast.lng
  • myData.square.northeast.lat
  • myData.square.southwest.lng
  • myData.square.southwest.lat

仅使用这些,您就可以使用 .textContent 属性填充 HTML。


工作示例:

const myJSON = `

{
  "country": "GB","square": {
      "southwest": {
          "lng": -0.119971,"lat": 51.517491
      },"northeast": {
          "lng": -0.119927,"lat": 51.517518
      }
  },"nearestPlace": "Clerkenwell,London","coordinates": {
      "lng": -0.119949,"lat": 51.517505
  },"words": "shield.mats.windy","language": "en","map": "https://w3w.co/shield.mats.windy"
}

`;

const myData = JSON.parse(myJSON);
const nelng = document.querySelector('table .northeast .longitude');
const nelat = document.querySelector('table .northeast .latitude');
const swlng = document.querySelector('table .southwest .longitude');
const swlat = document.querySelector('table .southwest .latitude');

nelng.textContent = myData.square.northeast.lng;
nelat.textContent = myData.square.northeast.lat;
swlng.textContent = myData.square.southwest.lng;
swlat.textContent = myData.square.southwest.lat;
thead,td:first-of-type {
    font-weight: bold;
    color: #fff;
    background-color: #3f87a6;
}

tbody {
    background-color: #e4f0f5;
}

table {
    border-collapse: collapse;
    border: 2px solid rgb(200,200,200);
    letter-spacing: 1px;
    font-family: sans-serif;
    font-size: .8rem;
}

td,th {
    border: 1px solid rgb(190,190,190);
    padding: 5px 10px;
}

td {
    text-align: center;
}
<table>
  <thead>
    <tr>
      <th></th>
      <th>Longitude</th>
      <th>Latitude</th>
    </tr>
  </thead>
  
  <tbody>
    <tr class="northeast">
      <td>Northeast</td>
      <td class="longitude"></td>
      <td class="latitude"></td>
    </tr>
    
    <tr class="southwest">
      <td>Southwest</td>
      <td class="longitude"></td>
      <td class="latitude"></td>
    </tr>
  </tbody>
</table>