Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a JSON object loaded from a file?

Tags:

json

d3.js

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?

like image 363
Chang Avatar asked May 09 '13 05:05

Chang


People also ask

How do I save a JSON object?

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.

Can you store a file in JSON?

You can store JSON documents in SQL Server or SQL Database and query JSON data as in a NoSQL database.

How do I save a JSON string to a file?

Show activity on this post. Write a data in file using JSON use json. dump() or json. dumps() used.


2 Answers

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?

like image 66
Christopher Chiche Avatar answered Sep 27 '22 21:09

Christopher Chiche


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

like image 27
punstress Avatar answered Sep 27 '22 22:09

punstress