I have a JSON data which I can get from this
But when I do:
import * as data from "./data.json" assert { type: "json" };
console.log(data.default)
Then only I can view my JSON object like normal, i.e. what would the output have been if I did:
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();
Why does this happen? And is there any better method of importing my JSON file so that I can access it in my code?
CodePudding user response:
This happens because the import * as
line imports an_entire_modules_contents where cause the absence of an explicit export default
the default property coincides with the content of your json file. If you want the data
variable contains your json file you can use instead:
import {default as data} from "./data.json";
console.log(data); //<-- it will print the content of your json file