[英]How can I import and use data from a JSON file in my React app?
I've been programming in React for a couple days now and have come across an issue utilizing a JSON file.我已经在 React 中编程了几天,并且在使用 JSON 文件时遇到了一个问题。
I'm currently using a hard coded list of...我目前正在使用硬编码列表...
const vendorList = [
{
id: 0,
name: "Laerdal Medical Corporation",
sections: [
{
name: "Product",
payload: [
{id: 1, name: "ASL 5000 Lung Solution"},
]
},
{
name: "Demos",
payload: [
{id: 1, name: "ASL 5000 Lung Solution", url: "ASL 5000 Lung Solution - High Fidelity Lungs for SimMan and SimBaby (laerdal.com)", type: "video"}
]
To populate some "VendorCards".填充一些“供应商卡”。 I now have a JSON file with the same data in it...我现在有一个 JSON 文件,其中包含相同的数据......
{
"vendorList" : [
{
"id": 1,
"name": "Laerdal Medical Corporation",
"sections": [
{
"name": "Products",
"payload": [
{"id": 1, "name": "ASL 5000 Lung Solution"}
]
},
{
"name": "Demos",
"payload": [
{"id": 1, "name": "ASL 5000 Lung Solution", "url": "ASL 5000 Lung Solution - High Fidelity Lungs for SimMan and SimBaby (laerdal.com)", "type": "video"}
]
}
],
"tags": ["Tag 1","Tag 2"]
}]
How do I go about changing from my hardcoded list, to my JSON object?如何从我的硬编码列表更改为 JSON object? I am able to import the JSON object after reading other stackoverflow questions using import myJson from './data.json'
, but can't figure out how to put the json object in vendorlist
. I am able to import the JSON object after reading other stackoverflow questions using import myJson from './data.json'
, but can't figure out how to put the json object in vendorlist
. Thanks for your time!谢谢你的时间!
From your comments it looks like the JSON is being imported using从您的评论看来,JSON 正在使用
import myJson from ./data.json';
which I then assume it is being automatically parsed.然后我假设它正在被自动解析。 (So no need for JSON.parse
) (所以不需要JSON.parse
)
After this, it is only a matter of pushing the data into vendorlist
.在此之后,只需将数据推送到vendorlist
。
vendorlist.push(...myJson.vendorList);
If you don't want to mutate vendorlist
you can also create a new array by combining the two.如果您不想改变vendorlist
,您也可以通过组合两者来创建一个新数组。
const newlist = [...vendorlist, ...myJson.vendorList];
// or
const newlist = vendorlist.concat(myJson.vendorList);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.