Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import json data in D3?

How do I import json file in D3?

I did 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

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.

like image 654
sweety pie Avatar asked Jan 14 '23 15:01

sweety pie


1 Answers

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(error, data){
    //use data here
})
// do not use data anymore
like image 86
Christopher Chiche Avatar answered Jan 17 '23 17:01

Christopher Chiche