I am using this to parse a csv file and create an array data as specified in d3 docs:
d3.tsv("classes_h.txt", function(data) {
data.forEach(function(d) {
console.log(data[0]);
console.log("lol");
});
console.log(data[0]);
});
or
d3.tsv("classes_h.txt", function(data) {
console.log(data[0]);
});
However I get undefined in the console when I call the data[0]. I've also tried writing out "data instead of "data[0]" which result in me getting an empty array -> []:
My txt file looks like this: http://puu.sh/7LrRm.png
Everything is seperated with a tab, so tsv is what I'm using and if I have understood it correctly, whether tsv or csv is used depends on the format the data is in?
Thanks in advance.
SOLVED
TSV doesn't just take tab seperated elements a throw them into an array. You the format to look like this:
Group1 Group2 Group3
data1 data1 data1
data2 data2 data2
data3 data3 data3
Then you can print out and verify that the data is loaded:
data.forEach(function(d) {
console.log(d);
});
When printing out the entire data D3 will create an objects that each have a Group bound with all of it's data. Here's the output of my example:
Object {Group1: "data1", Group2: "data1", Group3: "data1"}
Object {Group1: "data2", Group2: "data2", Group3: "data2"}
Object {Group1: "data3", Group2: "data3", Group3: "data3"}
Those the objects are equivalent to data[0], data[1] and data[2], which leaves group1, group2 and group3.
Is this localy hosted? If it is are you loading the page with the file://
protocol or is it been served over http (eg http://localhost:8080
).
If it is using file://
then you will be having problems as the browser will not allow the file to be loaded with a XMLHttpRequest
which d3.tsv()
uses to fetch the file.
Alternatively follow Lars' advice and check for an error
d3.tsv("file.tsv", function(error, data){
if(error){
return console.log(error);
}
// there was no error
});
Changing the data[0] to d.header of data you want displayed should work.
d3.tsv("classes_h.txt", function(data) {
data.forEach(function(d) {
console.log(d.*displaydata*);
console.log("lol");
});
来源:https://stackoverflow.com/questions/22690168/how-to-get-data-with-tsv-or-csv-to-array-in-d3-js-from-a-txt-file