PC3SQ
PC3SQ

Reputation: 135

Using D3 to read csv returns html instead of csv data

I have the following d3 code within script tags:

  d3.csv("data.csv", function(error, data) {
    data.forEach(function(d) {
      console.log(data[0]);

      d.date = parseDate(d.date);
      d.close = +d.close;
    });
    console.log("hello2")

    // Scale the range of the data
    x.domain(d3.extent(data, function(d) { return d.date; }));

    y.domain([0, d3.max(data, function(d) { return d.close; })]);

    svg.append("path") // Add the valueline path.
    .attr("class", "line")
    .attr("d", valueline(data));

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

    svg.append("g") // Add the Y Axis
    .attr("class", "y axis")
    .call(yAxis);

  });

When I check the console in my browser, the output for the console.log was Object {<!DOCTYPE html>: "</head>"}. I'm expected the output to be {"date": "1-May-12", close: "58.13"}.

Why is the callback function using my html as the data parameter rather than my CSV data? Note that I am also running a simple node server so I can read the CSV.

Upvotes: 4

Views: 1757

Answers (2)

PC3SQ
PC3SQ

Reputation: 135

Let's start from the beginning ... I was trying to read the local csv data.csv from the same folder as my html containing the D3 script. That didn't work because there are built in browser security measures that prevent you from reading from your local machine. Without realizing that was what was causing an issue, I read other SO answers that led me to write my own node server to locally serve up my html and csv. That's when the bug that led me to create this SO question occurred.

The problem now was that when my D3 script was trying to read data.csv, it was reading the html file the D3 script was contained in; D3 was read in basic_chart.html instead of data.csv. That's why I was getting an object with key-value pairs describing an html file rather than a csv. I determined this had something to do with my server script but instead of rewriting the server script, I used the best answer from D3.js loading local data file from file:/// and served up my html and csv by typing python -m SimpleHTTPServer 8888 & on the command line while inside the target files' folder. It worked. Hope this helps someone else out. Thanks for your help @Cyril.

Upvotes: 3

Cyril Cherian
Cyril Cherian

Reputation: 32327

Your CSV should not be a one liner

Should be like this:

date,close
1-May-12,58.13
30-Apr-12,53.98
27-Apr-12,67.00
26-Apr-12,89.70
25-Apr-12,99.00

then you can read the csv like this

 d3.csv("data.csv", function(error, data) {
    var parseDate = d3.time.format("%d-%b-%y");
    data.forEach(function(d) {
      d.date = parseDate.parse(d.date);
      d.close = +d.close;
    });
    console.log(data)
 })

working code here

Upvotes: 0

Related Questions