2017-02-16 503 views
3

我只是在理解D3的文档CSV Parse时遇到了一点麻烦。我目前有:如何用d3读取CSV文件?

d3.parse("data.csv",function(data){ 
    salesData = data; 
}); 

但我一直得到错误:

Uncaught TypeError: d3.parse is not a function

这是什么应该是什么样子的?我只是有点困惑,我能找到的唯一例子就像this

我也试过类似:

d3.dsv.parse("data.csv",function(data){ 
    salesData = data; 
}); 

,并得到:

Uncaught TypeError: Cannot read property 'parse' of undefined

这究竟是为什么?任何帮助将大大appreaciated,谢谢!

回答

6

有一些误解,在这里:你混淆d3.csv,这是一个请求,以d3.csvParse,它解析字符串(也混合具有D3 v4功能的D3 v3功能)。这就是区别:

d3.csv

d3.csv功能,这需要作为参数(url[[, row], callback])

Returns a new request for the CSV file at the specified url with the default mime type text/csv. (emphasis mine)

所以,你可以看到,您使用d3.csv当你想请求给定CSV文件在给定的网址。

例如,下面的代码片段获取CSV在引号之间的URL,它看起来像这样...

name, parent 
Level 2: A, Top Level 
Top Level, null 
Son of A, Level 2: A 
Daughter of A, Level 2: A 
Level 2: B, Top Level 

...并记录解析CSV文件,检查:

d3.csv("https://gist.githubusercontent.com/d3noob/fa0f16e271cb191ae85f/raw/bf896176236341f56a55b36c8fc40e32c73051ad/treedata.csv", function(data){ 
 
    console.log(data); 
 
});
<script src="https://d3js.org/d3.v4.min.js"></script>

d3.csvParse

在另一方面,d3.csvParse(或D3 V3 d3.csv.parse),这需要作为参数(string[, row])

Parses the specified string, which must be in the delimiter-separated values format with the appropriate delimiter, returning an array of objects representing the parsed rows.

所以,你用d3.csvParse当你要解析的字符串。

这里是一个演示,假设你有这样的字符串:

var data = "foo,bar,baz\n42,33,42\n12,76,54\n13,42,17"; 

如果要分析它,你将使用d3.csvParse,不d3.csv

var data = "foo,bar,baz\n42,33,42\n12,76,54\n13,42,17"; 
 

 
var parsed = d3.csvParse(data); 
 

 
console.log(parsed);
<script src="https://d3js.org/d3.v4.min.js"></script>

1

使用d3.csv("data.csv", function(data){...})从url中获取CSV并解析,或者使用d3.csv.parse()解析CSV格式的字符串。

1

你可以得到CSV数据到D3类似如下 -

// get the data 
d3.csv("data.csv", function(error, data) { 
    if (error) throw error; 
     console.log(data); 
     //format data if required... 
     //draw chart 
} 
1

这里是您可以使用d3.js读取csv文件的代码

<script src="https://d3js.org/d3.v4.min.js"></script> 
<script> 
d3.csv("csv/cars.csv", function(data) { 
console.log(data[0]); 
}); 
</script> 

请注意,csv文件名是“cars.csv”,并且该文件保存在名为csv的文件夹中。

console.log(data[0]) 

将帮助您在浏览器调试窗口中看到数据输出。在哪里,你也可以找到是否有任何错误。