0

I loaded a json object using d3.json and assigning the loaded json file to a global variable but when I print the global variable to the console it returns undefined, but when i type in the global variable in the chrome console it returns what I need it to. Essentially, I am just looking to load the json object be able to use it outside the d3.json function. This seems like a relatively simple task but I am a js/d3 newby so any help is greatly appreciated!

Thanks!

Code is provided below

    <script type = "text/javascript" source='https://d3js.org/d3.v4.min.js'>

var gapminder;

d3.json("D3_jsondata.json", function(data){
  gapminder = data;
});
//above prints in console when i type in gapminder

console.log(gapminder);//prints as 'undefined' in Chrome's console
</script>
OK_Sooner
  • 131
  • 1
  • 1
  • 7

2 Answers2

1

Calling .json() gets you a promise for the body of the http response that is yet to be loaded. Try to start rendering inside the callback of the json!

  • The json array prints inside the d3.json function. However, once I am in the function and start trying to append the svg to the body, nothing is rendering on the screen. It appends and renders when I use dummy data outside of d3.json – OK_Sooner May 21 '17 at 23:04
  • @OK_Sooner: Markus' advice is correct (this answer could be better elaborated, though). If you still have issues, you have **another** problem then. That being the case, post a new question specifying it. – Gerardo Furtado May 22 '17 at 00:28
0

For d3.json, d3.csv and d3.tsv are asynchronous request functions, so the console.log() will run before d3.json() where "gapminder" is still undefined.

After the console.log() then it's the term of d3.json() to run and you make a assignment "gapminder" with the json data, so it's not undefined anymore.

1Cr18Ni9
  • 1,737
  • 1
  • 12
  • 21