如何存储从文件加载的JSON对象?
问题描述:
我想将一个加载的JSON对象存储在变量中。
通常我应该这样做:
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; });
但是,我想要的是:
var jsonData = d3.json("jsondatafile.json");
我想访问 jsonData
code> d3.json 函数。
I want to access jsonData
outside the d3.json
function. How can I do this?
答
根据Scott Murray的Web数据交互(第74页),您可以先声明一个全局变量。在回调函数中,将数据分配给全局变量。
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