4

What is the best way in 2018 to read in a CSV file that has no header row using d3.js?

CSV

"d1","d2","d3"
"dx","dy","dz"
"d4","d5","d6"

This is what I’ve got from another Stack:

d3.text("data.csv", function(text) {
  const data = d3.csv.parseRows(text, function(d) {
    return d.map(String);
  });
  console.log(data);
});

Yet, I get no console output. What’s the mistake?

Kalaschnik
  • 769
  • 1
  • 7
  • 21
  • All d3 functions that used XHR (d3.text, d3.csv, d3.tsv, d3.json...) moved to promises now. – Gerardo Furtado Jun 21 '18 at 09:40
  • 2
    @GerardoFurtado I wouldn't consider this a duplicate; there is more to it than just the switch to the Fetch API. – altocumulus Jun 21 '18 at 11:15
  • Thanks for the Link you provided @GerardoFurtado; it works for reading it in as plain text: `d3.text("data.csv").then(function (data) { console.log(data); });` Yet its not when I try to combine with another then to parse the Rows... – Kalaschnik Jun 21 '18 at 12:11

1 Answers1

1

Since you're using D3 v5, the pattern described in that answer (which is 6 years old) doesn't work anymore: unlike previous versions, which used XMLHttpRequest, the new version uses promises.

That alone qualifies your question as a duplicate. However, I'm writing this answer because there is an important piece of code missing in your question: the piece that adds the header row.

So, since this is v5, this is the pattern you have to use:

d3.text("data.csv").then(function(data){
    //....
})

Inside the callback, you have to add the first row:

data = "foo,bar,baz\n" + data;

Then, you can parse it, using d3.csvParse:

var newData = d3.csvParse(data);

Because we can't use d3.text in the S.O. snippet, here is a bl.ocks with the demo: https://bl.ocks.org/GerardoFurtado/8849016b91b41ae463408c747417af95/8b299a22639621ae7619628a5b10fb9257783b8d

Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
  • BTW, I also [commented](https://gist.github.com/GerardoFurtado/8849016b91b41ae463408c747417af95#gistcomment-2626088) on your gist: "Why would you add a header row to it? To stick to the question's original code you could just use d3.csvParseRows(), right?" This, obviously, does also apply to your now undeleted answer. – altocumulus Jun 21 '18 at 13:01
  • @altocumulus now I'm totally lost: why did you say that *"there is more to it"*? – Gerardo Furtado Jun 21 '18 at 13:04
  • What I meant was: Not only the Fetch API but also the parsing: `d3.csv.parseRows` → `d3.csvParseRows`. Your answer started off in the right direction covering both issues but got somewhat lost when needlessly introducing a header row which OP did not ask for. – altocumulus Jun 21 '18 at 13:09