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

344
Visualizações
How to import JSON file to hold within a javascript variable

I have been searching for hours to make a javascript variable that holds that data from an imported JSON object. I can't find anything that comes close to helping me figure it out. Every time I search this topic it just brings me to tutorials on how to initiate a JSON file in js for external use. I am trying to use the variable with the JSON object with D3.js. This is the basic code from my last attempt:

const dataset =
  document.addEventListener('DOMContentLoaded', function(){
    fetch('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json')
      .then(response => response.json())
      .then(data => data.data);
  });
console.log(dataset);

I know that I can put the console.log within the fetch().then() method, but in order to use it with D3.js the way I want to it needs to be a global variable. I have tried to initialize the variable within the fetch() method, but that doesn't allow me to use it globally. I have also tried this sort of code:

var dataset = [];
  document.addEventListener('DOMContentLoaded', function(){
    fetch('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json')
      .then(response => response.json())
      .then(data => dataset = data.data);
  });
console.log(dataset);

As you might expect the dataset remains an empty array.

---Update---
Here is the codepen project: https://codepen.io/critchey/pen/YzEXPrP?editors=0010

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

0

This one should work:

const dataset = await fetch('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json')
  .then(response => response.json())
  .then(data => data.data);

The other way is:

let dataset;
fetch('https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json')
  .then(response => response.json())
  .then(data => dataset = data.data);

but value of dataset will be no available just after this code, but once Promise is resolved. So again you should add await before fetch to wait for Promise.

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