为什么JS代码导入JSON文件需要默认
Why is default required in importing JSON file in JS code
我有一个 JSON 数据可以从这个 API 中得到。
但是,当我将此 link 的内容复制到本地文件并将其另存为 JSON,然后在 JS 中导入时,如:
import * as data from "./data.json" assert { type: "json" };
console.log(data)
我在我的控制台中得到一个模块,其中默认参数包含我的 JSON 对象。
但是当我这样做时:
import * as data from "./data.json" assert { type: "json" };
console.log(data.default)
然后只有我可以正常查看我的 JSON 对象,即如果我这样做,输出会是什么:
async function populate() {
const requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
const request = new Request(requestURL);
const response = await fetch(request);
const superHeroes = await response.json();
console.log(superHeroes)
}
populate();
为什么会这样?有没有更好的方法导入我的 JSON 文件,以便我可以在我的代码中访问它?
发生这种情况是因为 import * as
行导入 an_entire_modules_contents 导致缺少显式 export default
default 属性与您的 json 文件的内容一致。如果您希望 data
变量包含您的 json 文件,您可以使用:
import {default as data} from "./data.json";
console.log(data); //<-- it will print the content of your json file
或下面的简单 shorthand:
import data from "./data.json";
我有一个 JSON 数据可以从这个 API 中得到。 但是,当我将此 link 的内容复制到本地文件并将其另存为 JSON,然后在 JS 中导入时,如:
import * as data from "./data.json" assert { type: "json" };
console.log(data)
我在我的控制台中得到一个模块,其中默认参数包含我的 JSON 对象。
但是当我这样做时:
import * as data from "./data.json" assert { type: "json" };
console.log(data.default)
然后只有我可以正常查看我的 JSON 对象,即如果我这样做,输出会是什么:
async function populate() {
const requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
const request = new Request(requestURL);
const response = await fetch(request);
const superHeroes = await response.json();
console.log(superHeroes)
}
populate();
为什么会这样?有没有更好的方法导入我的 JSON 文件,以便我可以在我的代码中访问它?
发生这种情况是因为 import * as
行导入 an_entire_modules_contents 导致缺少显式 export default
default 属性与您的 json 文件的内容一致。如果您希望 data
变量包含您的 json 文件,您可以使用:
import {default as data} from "./data.json";
console.log(data); //<-- it will print the content of your json file
或下面的简单 shorthand:
import data from "./data.json";