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; });
But, instead, I want something like:
var jsonData = d3.json("jsondatafile.json");
I want to access jsonData
outside the d3.json
function. How can I do this?
To save the JSON object to a file, we stringify the json object jsonObj and write it to a file using Node FS's writeFile() function.
You can store JSON documents in SQL Server or SQL Database and query JSON data as in a NoSQL database.
Show activity on this post. Write a data in file using JSON use json. dump() or json. dumps() used.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With