4

D3.js has tsv and csv fetches. Let's say if we have data:

x  y 
1     3
  2.2     -1.8
 3  4

is it true that the data can actually be separated just by whitespaces? We can write a preprocessor to convert the file by splitting the file by whitespaces, such as

const data = `x  y 
1     3
  2.2     -1.8
 3  4`;

console.log(data.split("\n").map(line => line.trim().split(/\s+/).join("\t")).join("\n"));

But is there a way to use D3.js directly and fetch the data by the way like above?

1 Answer 1

2

You can set different delimiters in d3.dsv (which stands for delimiter-separated values), although comma (CSV) and tab (TSV) are by far the most common ones.

First, set the delimiter:

const whiteSpaceParser = d3.dsvFormat(" ");

Then, parse the file with the parse() method:

const data = whiteSpaceParser.parse(file);

Here is the demo:

const file = `x y
1 3
2.2 -1.8
3 4`;

const whiteSpaceParser = d3.dsvFormat(" ");
const data = whiteSpaceParser.parse(file, d3.autoType);

console.log(data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.12.0/d3.min.js"></script>

Since this is a Stack Overflow snippet I cannot use a real file, hence the template literal. For a real file (for instance, a txt file), just use d3.dsv with the space as the delimiter, like this:

d3.dsv(" ", "foo.txt").then((data) => {
    //code here
});
Sign up to request clarification or add additional context in comments.

2 Comments

what if the whitespace can have a mix of space and tab? What about whitespace before the first field -- will the first field be taken to be "empty" actually?
@nonopolarity for this solution the file needs to have the delimiter (in your case, whitespace) following the same rules of other DSVs, so the answer is no, no mix allowed. If you have a mix I suggest you use d3.text() and write your custom parser to parse the data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.