xkcd 105 xkcd 105 - 7 months ago 117
Javascript Question

Reading json data from a file in d3.js not working

This is a d3 code that generates a line graph from data.tsv file. However I want to input data in form of json. So what will be changes required here. There is a line marked with *'s .I have changed tsv to json but the code is not working.

<script>

var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;

var formatDate = d3.time.format("%d-%b-%y");
var x=12;
var x = d3.time.scale()
.range([0, width]);

var y = d3.scale.linear()
.range([height, 0]);

var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");

var yAxis = d3.svg.axis()
.scale(y)
.orient("left");

var line = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });

var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

d3.tsv("data.tsv", type, function(error, data) { ///////*****/////
if (error) throw error;

x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain(d3.extent(data, function(d) { return d.close; }));

svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);

svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Price ($)");

svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
});

function type(d) {
d.date = formatDate.parse(d.date);
d.close = +d.close;
return d;
}

</script>

Answer

First, you have to check if your JSON structure correctly matches the data in your TSV or CSV. For instance, suppose that this is your CSV:

foo, bar
4, 5
12, 2
3, 61

Your JSON should be like this:

[
 { 
   "foo": 4,
   "bar": 5
 },
 { 
   "foo": 12,
   "bar": 2
 },
 { 
   "foo": 3,
   "bar": 61
 }
]

That is, an array of objects. Sometimes, in very big and complex JSONs, it's easy to forget a comma or a brace. I use codebeautify to check:

http://codebeautify.org/jsonviewer

And, then, just change d3.tsv for d3.json:

d3.json("data.json", function(data){
    console.log(data); //just to check if it's all right
    //the rest of your code
});

NOTE: Contrary to d3.csv and d3.tsv, you cannot provide an accessor function to d3.json.

Comments