Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

343
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!