Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

345
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda