javascript 用js加载本地.csv并用d3.js处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18188823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:01:14  来源:igfitidea点击:

Load local .csv with js and process it with d3.js

javascripthtmld3.js

提问by thelama

I stuck on the following thing. I don't have a running local http-service so I'd like to handle my file loading otherwise.

我坚持以下事情。我没有正在运行的本地 http 服务,所以我想以其他方式处理我的文件加载。

First I created the following function, as suggested in some references.

首先,我按照一些参考资料中的建议创建了以下函数。

var fileArray = [];
function readSingleFile(evt) {
    //Retrieve the first (and only!) File from the FileList object
    var f = evt.target.files;
        window.array = []
        if (f) {
            var r = new FileReader();
                r.onload = function(e) { 
                var contents = e.target.result;
                window.array.push(contents);
                fileArray.push({name:f.name, contents: contents});
                }
                r.readAsText(f);
                console.log(fileArray);
                } else { 
                    alert("Failed to load file");
                }
            }
            document.getElementById('fileinput').addEventListener('change', readSingleFile, false);

Then I try to call the fileArray in a d3.csv function. But this is where I stuck - the console log just shows an empty array.

然后我尝试在 d3.csv 函数中调用 fileArray。但这就是我卡住的地方 - 控制台日志只显示一个空数组。

var dataset = []
                    d3.csv(fileArray, function(data) {
                    dataset = data.map(function(d) { return [ d["TEXT"], +d["HOURS"], +d["MONTH_DIGIT"] ]; });
                    console.log(dataset)
                });

The .csv file has the following structure.

.csv 文件具有以下结构。

"TEXT","HOURS","MONTH_DIGIT"
"Adjustments work",849.45,"01"

How do I exactly call the file to work with d3.js?

我如何准确调用文件以使用 d3.js?

回答by m_vdbeek

If you want to "take the file and it's contents and work with it", you could load the file inside the d3.csv()method, after the callback and the apply the changes you wanted to make to the content.

如果您想“获取文件及其内容并使用它”,您可以在d3.csv()方法中加载文件,在回调之后应用您想要对内容进行的更改。

d3.csv('/path/to/myfile.csv, function(data) {
    // Modify the files data
    ...
    // Do something with d3.js
});

回答by pilavdzice

For JSON:

对于 JSON:

var data = JSON.parse(JavascriptStringVariableThatContainsJSON);

For CSV:

对于 CSV:

 var data = d3.csv.parseRows(JavascriptStringVariableThatContainsMyCSVdata);

//then add data to the graph and call enter, something like:

//然后向图中添加数据并调用回车,例如:

 var dataEnter = svg.selectAll("rect").data(data).enter();