如何在D3中导入json数据?

时间:2023-02-03 21:16:18

How do I import json file in D3?

如何在D3中导入json文件?

I did d3.json("temp.json");

我做了d3.json(“temp.json”);

But how do I access this data set in further code?

但是如何在更多代码中访问此数据集?

So far I have tried:

到目前为止,我尝试过:

var data=d3.json("temp.json");

But using .data(data) did not work in rest of the code. For example, here

但是使用.data(数据)在其余代码中不起作用。例如,这里

var rows = g.selectAll("g.row")
.data(data)
.enter().append("g")
.attr({
  "class": "row",
  "transform": function(d, i) {
    var tx = 170 + i * squareWidth;
    var ty = 150;
    return "translate(" + [tx, ty] + ")"
  }
});

It is not able to access the data. I copy pasted the json into variable and it worked fine. So there is no problem with the data itself.

它无法访问数据。我复制粘贴json到变量,它工作正常。所以数据本身没有问题。

1 个解决方案

#1


8  

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(error, data){
    //use data here
})
// do not use data anymore

#1


8  

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(error, data){
    //use data here
})
// do not use data anymore