首页 > 解决方案 > 如何使用 API 调用从嵌套 JSON 中检索数据并使用 js 将其显示在网页上

问题描述

我只能从第一个字段中获取和显示 JSON 内容,无法访问任何其他字段。

我只能从第一个 JSON 字段中获取ua,无法从第二个 JSON 字段中获取family 。

它在控制台选项卡中给出错误

未捕获(承诺中)TypeError:无法在 getData 处设置属性“textContent”为 null

js代码

<script>
       function myFunction() {
        var x = navigator.userAgent;
        const newText = x.split(/\s/).join('');
        document.getElementById("demo").innerHTML = x;
        const text = document.getElementById('demo').textContent;
         const api_url = 'http://api.userstack.com/detect?access_key=<key>&ua=';
           async function getData() {
            const response = await fetch(api_url + newText);
            const data = await response.json();
            const { ua,  family} = data;
            document.getElementById('ua').textContent = ua;
            document.getElementById('family').textContent = os;
       }
       getData();
       }
</script>

JSON

{
  "ua":"browser agent",
  "type":"browser",
  "brand":null,
  "name":null,
  "url":"https:\/\/about.google\/",
  "os":{
    "name":"Windows 10",
    "code":"windows_10",
    "url":"https:\/\/en.wikipedia.org\/wiki\/Windows_10",
    "family":"Windows",
    "family_code":"windows",
    "family_vendor":"Microsoft Corporation.",
    "icon":"https:\/\/assets.userstack.com\/icon\/os\/windows10.png",
    "icon_large":"https:\/\/assets.userstack.com\/icon\/os\/windows10_big.png"
  },
  "device":{
    "is_mobile_device":false,
    "type":"desktop",
    "brand":null,
    "brand_code":null,
    "brand_url":null,
    "name":null
  },
  "browser":{
    "name":"Chrome",
    "version":"82.0",
    "version_major":"92",
    "engine":"WebKit\/Blink"
  },
  "crawler":{
    "is_crawler":false,
    "category":null,
    "last_seen":null
  }
}

标签: javascriptjson

解决方案


您正在尝试family直接访问,但它是os. 因此,您必须将 const 更改为:

const { ua,  os:{family}} = ans;

推荐阅读