Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

284
Visualizações
Why is default required in importing JSON file in JS code

I have a JSON data which I can get from this API. However when I copy the contents of this link into a local file and save it as JSON, and then import in in JS like:

import * as data from "./data.json" assert { type: "json" };

console.log(data)

I am getting a module in my console where the default parameter contains my JSON object.enter image description here

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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

Or the simple shorthand below:

import data from "./data.json";
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda