javascript - 如何使用 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
}
}
解决方案
您正在尝试family
直接访问,但它是os
. 因此,您必须将 const 更改为:
const { ua, os:{family}} = ans;
推荐阅读
- php - NGINX 和 PHP-FPM (7.4) 在 ubuntu 404 上通过 javascript 访问的 .php 文件
- amazon-web-services - 无法将数组传递给 AWS StepFunction 中的参数
- python - 试图在 tkinter 中打印我的菜单 gui 的总成本。ERROR = 'int' 对象不可调用
- python - 人类时间和日期时间?
- c++ - 当两个库有同名的变量类型时,如何正确定义变量类型?
- javascript - 交叉点观察者 API 出现在滚动条上
- docker - Docker 容器和隐藏的 CPU 利用率
- excel - 如何获得动态数组的每一行的总和?
- javascript - 将 url 参数替换为 jquery 中选定的列表值
- c++ - 使用 clang 编译时避免使用 xxx.dSYM