如何存储从文件加载的JSON对象?

[英]How to store a JSON object loaded from a file?


I want to store a loaded JSON object in a variable. Normally I should do something like:

我想将一个加载的JSON对象存储在一个变量中。通常我应该这样做:

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?

我想访问d3.json函数之外的jsonData。我怎样才能做到这一点?

2 个解决方案

#1


6  

You can always use jQuery.ajax() synchronously:

您始终可以同步使用jQuery.ajax():

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:

但是不推荐使用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.

Ajax中的第一个字母代表“异步”,意味着操作并行发生,并且不能保证完成的顺序。 $ .ajax()的async选项默认为true,表示在发出请求后代码执行可以继续。将此选项设置为false(从而使调用不再异步)是强烈建议不要的,因为它可能导致浏览器无响应。

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()是异步的。因此,您必须在读取数据变量之前等待接收数据。这就是为什么在处理异步数据时,实践是在d3.json()函数中执行所有操作:

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?

注意:答案来自我之前的答案:如何在D3中导入json数据?

#2


5  

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.

根据Scott Murray的Web数据交互式数据(第74页),您可以先声明一个全局变量。在回调函数内部,将数据分配给全局变量。

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

数据集可用于所有后续功能


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/05/09/99e4cbbd9b7c822915daa9b52f43b9e3.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com