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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With