Javascript 将csv文件转换为json对象数据表

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

convert csv file to json object datatable

javascriptasp.netapicharts

提问by locoboy

Does anyone know how to get a csv url file and convert it to a json object so that I can use google charting tools in js?

有谁知道如何获取 csv url 文件并将其转换为 json 对象,以便我可以在 js 中使用谷歌图表工具?

采纳答案by Matias

As far as I know, for most scenarios, you can turn csv into a js Array of Arrays, a Matrix, or any javascript object that follows your charting tool convention.

据我所知,对于大多数情况,您可以将 csv 转换为 js Array of Arrays、Matrix 或任何遵循您的图表工具约定的 javascript 对象。

You may need to:

您可能需要:

  1. Get the CSV file content
  2. Parse it
  3. Wrap the results from 2 into your charting tool json(?)
  4. Call your charting library
  1. 获取 CSV 文件内容
  2. 解析它
  3. 将 2 的结果包装到您的图表工具 json(?)
  4. 调用您的图表库

For 1, if the CSV file is hosted in your domain, you can do a simple XMLHttpRequest, else try searching here "same origin policy".
The tricky part is the point 2. I've seen several failed attempts for parsing CSV files by hand (semicolons can be contained as part of the value, etc)... Check out the link.

对于 1,如果 CSV 文件托管在您的域中,您可以执行简单的 XMLHttpRequest,否则尝试在此处搜索“同源策略”。
棘手的部分是第 2 点。我已经看到了几次手动解析 CSV 文件的失败尝试(分号可以作为值的一部分等)......查看链接。

回答by aaronsnoswell

I realise this is an old question, but I came across it today needing to do the same thing and wrote a script to do it. You can check it out at my github repo.

我意识到这是一个老问题,但我今天遇到了它需要做同样的事情并编写了一个脚本来做到这一点。你可以在我的github repo 中查看。

The following code would accomplish what you're after (using jQuery):

以下代码将完成您所追求的(使用 jQuery):

$.ajax("http://my.domain.com/mycsvfile.csv", {
    success: function(data) {
        var jsonobject = csvjson.csv2json(data);
        // Now use jsonobject to do some charting...
    },
    error: function() {
        // Show some error message, couldn't get the CSV file
    }
});

Happy coding :)

快乐编码:)

回答by Enrikisimo Lopez Ramos

use this code for guide to parse csv file to json ...

使用此代码作为指导将 csv 文件解析为 json ...

function processFiles(files) {
    var file = files[0];
    var reader = new FileReader();
    reader.onload = function (e) {
        var output = document.getElementById("fileOutput");
        var texto = e.target.result;
        csvJSON(texto);
    };
    reader.readAsText(file);
}
function csvJSON(csv) {
    var lines = csv.split("\n");
    var result = [];
    var headers;
    for (var i = 0; i < lines.length; i++) {
        headers = lines[i].split("\n");
    }
    var cont = 0;
    for (var i = 0; i < lines.length; i++) {

        var obj = {};
        var currentline = lines[i].split("\n");
        for (var j = 0; j < headers.length; j++) {
            obj[cont] = currentline[j];
        }
        cont++;
        result.push(obj);
    }

    return JSON.stringify(result); //JSON
}

回答by Stéphane Laurent

Papa Parseis nice for that.

Papa Parse对此很好。

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="libraries/PapaParse-4.1.2/papaparse.min.js"></script>

    <script>
    $(document).ready(function(){

        $("#submitbutton").click(function(){
            var myfile = $("#csvfile")[0].files[0];
            var json = Papa.parse(myfile, 
                {
                header: true, 
                skipEmptyLines: true,
                complete: function(results) {
                    console.log("Dataframe:", JSON.stringify(results.data));
                    console.log("Column names:", results.meta.fields);
                    console.log("Errors:", results.errors);
                }
            });

        })
    })
    </script>

</head>

<body>
    <form name="foo" method="post" enctype="multipart/form-data">
        <input id="csvfile" type="file" value="i">
    </form>

    <button id="submitbutton" type="button">Upload CSV file!</button>

</body>

</html>

Uploading this CSV:

上传此 CSV:

+------+----------------+---------------+------------+
|  Id  |  Petal.Length  |  Petal.Width  |  Species   |
+======+================+===============+============+
|  1   |      1.4       |      0.2      |   setosa   |
+------+----------------+---------------+------------+
|  2   |      1.4       |      0.2      |   setosa   |
+------+----------------+---------------+------------+
|  3   |      1.3       |      0.2      |   setosa   |
+------+----------------+---------------+------------+
|  4   |      3.9       |      1.4      | versicolor |
+------+----------------+---------------+------------+
|  5   |      3.5       |       1       | versicolor |
+------+----------------+---------------+------------+
|  6   |      4.2       |      1.5      | versicolor |
+------+----------------+---------------+------------+
|  7   |      5.4       |      2.3      | virginica  |
+------+----------------+---------------+------------+
|  8   |      5.1       |      1.8      | virginica  |
+------+----------------+---------------+------------+

you'll get this output in the console:

您将在控制台中获得此输出:

Dataframe: [{"Id":"1","Petal.Length":"1.4","Petal.Width":"0.2","Species":"setosa"},{"Id":"2","Petal.Length":"1.4","Petal.Width":"0.2","Species":"setosa"},{"Id":"3","Petal.Length":"1.3","Petal.Width":"0.2","Species":"setosa"},{"Id":"4","Petal.Length":"3.9","Petal.Width":"1.4","Species":"versicolor"},{"Id":"5","Petal.Length":"3.5","Petal.Width":"1","Species":"versicolor"},{"Id":"6","Petal.Length":"4.2","Petal.Width":"1.5","Species":"versicolor"},{"Id":"7","Petal.Length":"5.4","Petal.Width":"2.3","Species":"virginica"},{"Id":"8","Petal.Length":"5.1","Petal.Width":"1.8","Species":"virginica"}]
Column names: ["Id", "Petal.Length", "Petal.Width", "Species"]
Errors: []

回答by Darin Dimitrov

CSV and JSON are different formats. JSON is hierarchical while CSV represents a list of values. So I guess you will need to first parse the CSV (using a parserof course and not implementing yourself). This parser will give you an object which you could then serialize into JSON or probably convert into another object before serializing(once again using a parser) in order to get the desired format.

CSV 和 JSON 是不同的格式。JSON 是分层的,而 CSV 表示值列表。所以我想你需要首先解析 CSV(当然使用解析器不是自己实现)。该解析器将为您提供一个对象,然后您可以将其序列化为 JSON 或可能在序列化之前转换为另一个对象(再次使用解析器)以获得所需的格式。