gpt4 book ai didi

javascript - 如何在React js中解析本地JSON文件?

转载 作者:行者123 更新时间:2023-12-03 13:01:12 24 4
gpt4 key购买 nike

如何解析 JSON 文件,检索其所有数据并在我的代码中使用它?

我尝试导入文件并尝试控制台记录它,但它所做的只是打印 Object {}:

import jsonData from "./file.json";
console.log(jsonData);

这就是我的 file.json 的样子:

[
{
"id": 1,
"gender": "Female",
"first_name": "Helen",
"last_name": "Nguyen",
"email": "hnguyen0@bloomberg.com",
"ip_address": "227.211.25.18"
}, {
"id": 2,
"gender": "Male",
"first_name": "Carlos",
"last_name": "Fowler",
"email": "cfowler1@gnu.org",
"ip_address": "214.248.201.11"
}
]

我希望能够访问每个组件的名字和姓氏,并将其打印在网站上。

最佳答案

var data = require('../../file.json'); // forward slashes will depend on the file location

var data = [
{
"id": 1,
"gender": "Female",
"first_name": "Helen",
"last_name": "Nguyen",
"email": "hnguyen0@bloomberg.com",
"ip_address": "227.211.25.18"
}, {
"id": 2,
"gender": "Male",
"first_name": "Carlos",
"last_name": "Fowler",
"email": "cfowler1@gnu.org",
"ip_address": "214.248.201.11"
}
];

for (var i = 0; i < data.length; i++)
{
var obj = data[i];
console.log(`Name: ${obj.last_name}, ${obj.first_name}`);
}

https://jsfiddle.net/c9wupvo6/

关于javascript - 如何在React js中解析本地JSON文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37649695/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com