I want to store a loaded JSON object in a variable. Normally I should do something like:
d3.json(\"jsondatafile.json\", function(json){ DO SOMETHING; });
You can always use jQuery.ajax() synchronously:
var jsonData;
$.ajax({
dataType: "json",
url: "jsondatafile.json",
async: false
success: function(data){jsonData = data}
});
However it is not recommended as explained in jQuery API:
The first letter in Ajax stands for "asynchronous," meaning that the operation occurs in parallel and the order of completion is not guaranteed. The async option to $.ajax() defaults to true, indicating that code execution can continue after the request is made. Setting this option to false (and thus making the call no longer asynchronous) is strongly discouraged, as it can cause the browser to become unresponsive.
The function d3.json() is asynchronous. Thus, you have to wait for the data to be received before reading the data variable. This is the reason why, when dealing with asynchronous data, the practice is to do everything inside the d3.json() function:
d3.json("temp.json", function(data){
//use data here
})
// do not use data anymore
Note: answer inspired from my previous answer here: How to import json data in D3?
According to Interactive Data Vis for the Web by Scott Murray (p 74), you can first declare a global variable. Inside the callback function, assign the data to the global var.
var dataset; // global
d3.json("file.json", function(data) {
dataset = data;
//any other functions that depend on data
});
dataset is avail to all subsequent functions