如何在 Javascript 中读取数组中的 csv 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21798139/
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 21:43:17  来源:igfitidea点击:

How do I read csv file in an array in Javascript?

javascriptjqueryarrayscsvjquery-csv

提问by rishiag

This is my first time with javascript and I am stuck on a problem. I have to read from csv file which contains names of top 1 million websites based on Alexa traffic. The size of csv file is 22.5 MB. Based on some tutorials on net, I am trying to do like this:

这是我第一次使用 javascript,我遇到了一个问题。我必须从 csv 文件中读取,其中包含基于 Alexa 流量的前 100 万个网站的名称。csv 文件的大小为 22.5 MB。根据网上的一些教程,我正在尝试这样做:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>three.js webgl - interactive cubes</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
        <style>
            body {
                font-family: Monospace;
                background-color: #f0f0f0;
                margin: 0px;
                overflow: hidden;
            }
        </style>
    </head>
    <body>

        <script src="./three.min.js"></script>
        <script src="./jquery-2.1.0.min.js"></script>
        <script src="./stats.min.js"></script>
        <script src="./jquery.csv-0.71.js"></script>

        <script>
        var data = $.csv.toObjects('top_1m.csv');
        console.log(data);
        </script>

    </body>
</html>

But I am not getting any output on console except []. What is wrong with this? Also is the correct way to do this. Basically I need to read file one time in array and then use that array for further processing.

但是除了 [] 之外,我在控制台上没有得到任何输出。这有什么问题?也是这样做的正确方法。基本上我需要在数组中读取文件一次,然后使用该数组进行进一步处理。

回答by Segfault

There's a similar question to this here, you must have missed it.

有一个类似的问题,这在这里,你一定错过了它。

The CSVlibrary parses CSVstrings not files. The reason it gives you an empty array
is because it's not complete CSVi.e 1 header + 1 item at the very least.

CSV库解析CSV字符串而不是文件。它给你一个空数组的原因
是因为它不完整,CSV即至少 1 个标题 + 1 个项目。

Here's the documentation in the source code.

这是源代码中的文档。

LINE 673
    /**
     * $.csv.toObjects(csv)
     * Converts a CSV string to a javascript object.
     * @param {String} csv The string containing the raw CSV data.
     * @param {Object} [options] An object containing user-defined options.
     ...
     **/

As pointed out in the comments, processing a CSVfile as huge as that in the browser
is not a wise decision, it's best done at the server.

正如评论中指出的那样,处理CSV像在浏览器中一样大的文件
并不是一个明智的决定,最好在服务器上完成。

Here's one way you can open a file and process the contents.
NOTE: It only works in Firefox. Three.jslibrary chokes in IE 8. It complains
about syntax errors(??). You'll get a Uncaught exception: DOMException: NETWORK_ERR
with Opera.

这是打开文件并处理内容的一种方法。
注意:它仅适用于FirefoxIE 8 中的Three.js库阻塞。它抱怨 语法错误(??)。你会得到一个 与歌剧
Uncaught exception: DOMException: NETWORK_ERR

Also, you'll get a syntax errordue to parsing invalid(non) XML(i.e the CSVcontents)
in Firefox 19.0.2.

此外,syntax error由于 在Firefox 19.0.2 中解析 invalid(non) XML(即CSV内容),您会得到一个。

It's not the most elegant solution. It just works.

这不是最优雅的解决方案。它只是有效。

<!DOCTYPE html>
<html lang = "en">
    <head>
        <title>Testing CSV with jQuery csv.0.71</title>
        <meta charset = "utf-8">
        <script src = "./three.min.js"></script>
        <script src = "./jquery-2.1.0.min.js"></script>
        <script src = "./stats.min.js"></script>
        <script src = "./jquery.csv-0.71.js"></script>
        <script>

            function openCSVFile(CSVfileName){
                // create the object
                var httpRequest = new XMLHttpRequest();
                httpRequest.onreadystatechange = function() {
                    processCSVContents(httpRequest);
                }
                // Send the request
                httpRequest.open("POST", CSVfileName, true);
                httpRequest.send(null);
            }

            function processCSVContents(httpRequest){
                console.log("--> here");
                if (httpRequest.readyState == 4){
                    // everything is good, the response is received
                    if ((httpRequest.status == 200)
                    || (httpRequest.status == 0)){
                        // Analys the contents using the stats library
                        // and display the results
                        CSVContents = httpRequest.responseText;
                        console.log($.csv.toObjects(CSVContents));
                        console.log(" => Response status: " + httpRequest.status)
                        console.log(CSVContents);
                    } else {
                    alert(' => There was a problem with the request. ' 
                            + httpRequest.status + httpRequest.responseText);
                    }
                }
            }
        </script>
    </head>
    <body>
        <button type="button" onclick="openCSVFile('pets.csv');">Click Me!</button>
    </body>
</html>

The CSVfile, pets.csvcontains this:

CSV文件,pets.csv包含此:

name,age,weight,species
"fluffy",3,14,"cat"
"vesuvius",6,23,"fish"
"rex",5,34,"dog"

Output:

输出:

[{
    name: "fluffy",
    age: "3",
    weight: "14",
    species: "cat"
}, {
    name: "vesuvius",
    age: "6",
    weight: "23",
    species: "fish"
}, {
    name: "rex",
    age: "5",
    weight: "34",
    species: "dog"
}]

There's an alternative way of reading files locally, through HTML5's File API

有一种在本地读取文件的替代方法,通过HTML5 的文件 API