简体   繁体   English

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

[英]How do I read csv file in an array in Javascript?

This is my first time with javascript and I am stuck on a problem. 这是我第一次使用javascript,遇到了问题。 I have to read from csv file which contains names of top 1 million websites based on Alexa traffic. 我必须从csv文件中读取文件,该文件包含基于Alexa流量的排名前100万个网站的名称。 The size of csv file is 22.5 MB. csv文件的大小是22.5 MB。 Based on some tutorials on net, I am trying to do like this: 根据网上的一些教程,我正在尝试这样做:

<!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. 基本上,我需要一次读取数组中的文件,然后使用该数组进行进一步处理。

There's a similar question to this here , you must have missed it. 有一个类似的问题,这在这里 ,你一定错过了它。

The CSV library parses CSV strings not files. CSV库解析CSV字符串而不是文件。 The reason it gives you an empty array 它给你一个空数组的原因
is because it's not complete CSV ie 1 header + 1 item at the very least. 是因为它不是完整的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 CSV file as huge as that in the browser 正如评论中指出的那样,处理与浏览器中一样大的CSV文件
is not a wise decision, it's best done at the server. 这不是明智的决定,最好在服务器上完成。

Here's one way you can open a file and process the contents. 这是打开文件并处理内容的一种方法。
NOTE: It only works in Firefox . 注意:它仅在Firefox中有效 Three.js library chokes in IE 8 . IE 8中的 Three.js库阻塞。 It complains 它抱怨
about syntax errors(??). 关于语法错误(??)。 You'll get a Uncaught exception: DOMException: NETWORK_ERR 您将收到Uncaught exception: DOMException: NETWORK_ERR
with Opera . 歌剧

Also, you'll get a syntax error due to parsing invalid(non) XML (ie the CSV contents) 此外,由于解析无效的(非) XML (即CSV内容),您还会收到syntax error
in Firefox 19.0.2 . Firefox 19.0.2中

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 CSV file, pets.csv contains 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的File API ,还有另一种本地读取文件的方式

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

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