stackyyflow stackyyflow - 2 months ago 15
JSON Question

D3 heatmap convert code to use json instead of tsv

I am trying to use D3 heatmap: http://bl.ocks.org/tjdecke/5558084 but had trouble changing the code. The example shows the use of .tsv files but I want to use .json file instead.

So instead of tsvFiles code as show below:

var heatmapChart = function(tsvFile) {
d3.tsv(tsvFile,
function(d) {
return {
day: +d.day,
hour: +d.hour,
value: +d.value
};
},
function(error, data) {
// eliminate code
});
};


I tried changing to json (but it does not work):

d3.json("./data/data.json",
function(d) {
return {
day: +d.day + 1,
hour: +d.hour + 1,
value: +d.value
};
},

function(error, data) {
// eliminate error
});

Answer

d3.json doesn't accept an accessor function, only d3.csv and d3.tsv accept it (the accessor function is that function between "data.json" and "function(error, data)" in your snippet).

So, change your d3.json function to:

d3.json("./data/data.json",  function(error, data) {
    //the rest of your code
});

And, in "the rest of your code", write the accessor function. In your case, something like this:

data.forEach(function(d) {
    return {
         day: +d.day + 1,
          hour: +d.hour + 1,
          value: +d.value
     };
 });

Also, this will only work if your JSON mimics exactly the structure of the array of objects created by d3.tsv.