简体   繁体   English

在.javascript中将.csv文件读取到对象/数组

[英]Read .csv file to object/array in javascript

I'm trying to do something that I think is fairly simple, but doesn't seem to be working. 我正在尝试做一些我认为相当简单的事情,但似乎并没有奏效。 I have a .csv file in the same directory as my script file. 我的.csv文件与我的脚本文件位于同一目录中。 I want to create an object or an array using the data from the .csv file. 我想使用.csv文件中的数据创建一个对象或数组。 How do I access the local file using javascript? 如何使用javascript访问本地文件?

Sorry for the lack of code, but I don't even know which route to go down; 很抱歉没有代码,但我甚至不知道要走哪条路线; I've tried .get and ajax and this plugin but I just don't know what I'm doing. 我试过.get和ajax以及这个插件,但我只是不知道我在做什么。 Could someone give me a clear example of how to load the file and print it in a div? 有人能给我一个明确的例子,说明如何加载文件并将其打印在div中?

In order to simulate a static file server, you can run an http server using python on the command line. 为了模拟静态文件服务器,您可以在命令行上使用python运行http服务器。 This is necessary to use ajax requests. 这是使用ajax请求所必需的。

python -m SimpleHTTPServer  

Or if you have python 3 或者如果你有python 3

python -m http.server

Now there are two parts to getting that file to a webpage. 现在有两个部分可以将该文件添加到网页中。 1) make an ajax request, 2) parse the csv. 1)发出ajax请求,2)解析csv。 There are many different libraries that implement ajax requests, but in this case you might find the easiest out of the box solution which combines both is d3.js . 有许多不同的库可以实现ajax请求,但在这种情况下,您可能会发现最简单的开箱即用解决方案,它结合了两个d3.js。

d3.csv("filename.csv", function(err, data) {

    // csv is parsed into an array of objects, as data

});

Of course this will only work if you are loading your page from localhost. 当然,这只有在从localhost加载页面时才有效。

EDIT: 编辑:

Make sure you run your http server from the location of your index.html file. 确保从index.html文件的位置运行http服务器。 then the request you make in the d3.csv function is relative to index. 那么你在d3.csv函数中提出的请求是相对于索引的。 finally, the data is only available inside the callback, and any error message (or null) will be put inside the err argument. 最后,数据仅在回调内可用,并且任何错误消息(或null)都将放在err参数中。

Project
|
+-- index.html
|    
+-- data
|  |  
|  \-- dataset.csv

Then the code in index.html would look like 然后index.html中的代码看起来像

d3.csv("data/dataset.csv", function(err, data) {

    if (err) console.log(err) // error messages

    console.log(data);   // should contain the parsed csv
});

PapaParse() does an excellent job here, for example this will do the job for you: PapaParse()在这里表现非常出色,例如这将为您完成工作:

Papa.parse(file, {
    complete: function(results) {
        console.log("Finished:", results.data);
    }
});

DEMO DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM