简体   繁体   中英

How can I import a json file in a JavaScript file?

I have two files data.json and index.js .

data.json looks like this:

{
      "stacy": {
           "age": 24,
           "name": "Stacy",
           "properties": [ "crazy", "funny", "straight" ]
      },
      "john": {
           "age": 41,
           "name": "John",
           "properties": [ "experienced", "direct", "straight" ]
      },
}

How can I import data.json into index.js ?

I thought about something like this: import * as persons from data.json;

You will find all of your JSON data in the data variable.

By using fetch API you can load JSON data. Code below:

fetch('data.json')
  .then(res => {
    return res.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(err => console(err));

try to write the exact file location.

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