How to store a JSON object loaded from a file?

后端 未结 2 1668
温柔的废话
温柔的废话 2020-12-11 19:26

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; });


        
相关标签:
2条回答
  • 2020-12-11 19:38

    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?

    0 讨论(0)
  • 2020-12-11 19:38

    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

    0 讨论(0)
提交回复
热议问题