如何存储从文件加载的 JSON 对象? [英] How to store a JSON object loaded from a file?

查看:28
本文介绍了如何存储从文件加载的 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; });

但是,相反,我想要类似的东西:

But, instead, I want something like:

var jsonData = d3.json("jsondatafile.json");

我想在 d3.json 函数之外访问 jsonData.我该怎么做?

I want to access jsonData outside the d3.json function. How can I do this?

推荐答案

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

You can always use jQuery.ajax() synchronously:

var jsonData;
$.ajax({
  dataType: "json",
  url: "jsondatafile.json",
  async: false
  success: function(data){jsonData = data}
});

但是不推荐,如 jQuery API 中所述:

However it is not recommended as explained in jQuery API:

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

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.

函数d3.json() 是异步的.因此,在读取 data 变量之前,您必须等待接收到数据.这就是为什么在处理异步数据的时候,所有的做法都是在d3.json()函数里面做的原因:

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

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

Note: answer inspired from my previous answer here: How to import json data in D3?

这篇关于如何存储从文件加载的 JSON 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆