sweety pie
sweety pie

Reputation: 41

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.

Upvotes: 4

Views: 10367

Answers (1)

Christopher Chiche
Christopher Chiche

Reputation: 15325

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

Upvotes: 9

Related Questions