简体   繁体   中英

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.

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...

{
    "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? 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

import myJson from ./data.json';

which I then assume it is being automatically parsed. (So no need for JSON.parse )

After this, it is only a matter of pushing the data into vendorlist .

vendorlist.push(...myJson.vendorList);

If you don't want to mutate vendorlist you can also create a new array by combining the two.

const newlist = [...vendorlist, ...myJson.vendorList];
// or
const newlist = vendorlist.concat(myJson.vendorList);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM