jyonkheel
jyonkheel

Reputation: 463

d3.js use a function as csv source instead of a csv path

I'm new to d3.js, when loading data, examples I've seen so far looks like

d3.csv("path/to/file.csv")...

I have a function that returns a dynamic server side generated csv, i use synchronous POST ajax to generate them, but for simplicity's sake lets say, I have a js function like this

function makeCSV(){
    return "id,value\n"+
           "0,value 1\n"+
           "1,value 2\n"+
}

is there a way to do something like this? and is this approach recommended at all (synchronous ajax is sure to cause lag)

d3.csv(makeCSV())...

other related concerns about CSV data loading is, is it required that .csv file is served, or would it be possible to simply put URL that makes and downloads a dynamically generated csv file, this could work as a replacement for AJAX call but manually encoding each parameter looks tedious and non-dynamic

d3.csv("?action=makeCSV&param1=val1&param2=val2")...

Upvotes: 1

Views: 221

Answers (1)

altocumulus
altocumulus

Reputation: 21578

According to the spec d3.csv() requires the first argument be the url to load the CSV from. If you want to just parse a string containing your CSV's content no matter how this was created, you need to use d3.csv.parse() instead. For your code this would be some like this

var rows = d3.csv.parse(makeCSV());

function makeCSV(){
    return "id,value\n"+
           "0,value 1\n"+
           "1,value 2\n";
}

var rows = d3.csv.parse(makeCSV())

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

Upvotes: 2

Related Questions