如何使用 javascript 访问 json 文件 (API) 中的元素? [英] How do I can I access elements in json file (API) using javascript?

查看:25
本文介绍了如何使用 javascript 访问 json 文件 (API) 中的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试显示此 JSON 文件中的所有名称,

I am trying to display all names in this JSON file,

https://next.json-generator.com/api/json/get/41P1_UhSI

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>testing</title>
</head>
<body>
    <script>
       
        const api_url = 'https://next.json-generator.com/api/json/get/41P1_UhSI'; 
        async function getAPI() {
            const response = await fetch(api_url);
            const data = await response.json();
            console.log(Object.values(data.name)); //or console.log(data.name);
        }
        getAPI();
    </script>
    
</body>
</html>

我收到一个错误:未定义"当我运行此代码时.

I am getting an error: "undefined" when I run this code.

如果有人能指出我正确的方向,那就太好了,谢谢!

Would be great if anyone could point me in the right direction, thanks!

推荐答案

data 不是具有 name 属性的对象,所以 name> 未定义.

data isn't an object with a name property, so name is undefined on it.

data 是一个数组,包含许多具有name属性的对象.

data is an array containing many objects with name properties.

这篇关于如何使用 javascript 访问 json 文件 (API) 中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆