有一些误解,在这里:你混淆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>