将CSV记录解析为JavaScript中的对象数组

dgiusagp  于 2023-02-20  发布在  Java
关注(0)|答案(5)|浏览(139)

我是新的JS和没有太多的经验,在正则表达式玩字符串操纵。
这是我的CSV文件,以表格形式与记录的第一行作为标题,从下一行的值将出现:

Name  City   Country
John  Chennai IN
Ken   Brisban AUS
Ben   NY      US

我需要对象数组中的输出,如下所示:

[
{Name: 'John',City: "Chennai",Country:"IN"}
{Name: 'Ken',City: "Brisbane",Country:"AUS"}
{Name: 'Ben',City: "NY",Country:"US"}
]

我正在上传一个CSV文件,需要将这些记录保存到DB中,下面是上传CSV后将触发的代码块,我尝试使用以下代码解析CSV记录:

$scope.processFiles = function() {
            //var input = document.getElementById("fileOutput");
            var input = document.querySelector('input[type = "file"]')
            var file = input.files[0];
            var reader = new FileReader();
            var output;
            reader.onload = function (e) {
                var csvToText = e.target.result;
                output = csvToJSON(csvToText);
                console.log(output);
            };
            reader.readAsText(file);
            event.preventDefault();
        }

        function csvToJSON(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);
            }
            console.log(result);
            //console.log(JSON.stringify(result));

            //return result;
        }

我得到的输出如下,即值显示在一行中,用逗号分隔,第四个数组元素不应该显示。

0: {0: "Name,City,Country"}
1: {1: "John,Chennai,IN"}
2: {2: "Ken,Brisbane,AUS"}
3: {3: "Ben,NY,USA"}
4: {4: ""}
4c8rllxm

4c8rllxm1#

我已经更正了您的函数,使其返回所需格式的输出:

function csvToJSON(csv) {
    var lines = csv.split("\n");
    var result = [];
    var headers;
    headers = lines[0].split(",");

    for (var i = 1; i < lines.length; i++) {
        var obj = {};

        if(lines[i] == undefined || lines[i].trim() == "") {
            continue;
        }

        var words = lines[i].split(",");
        for(var j = 0; j < words.length; j++) {
            obj[headers[j].trim()] = words[j];
        }

        result.push(obj);
    }
    console.log(result);
}
mpbci0fu

mpbci0fu2#

试试这个。

function csvToJSON(csv) {

    //lop off any trailing or starting whitespace
    csv = csv.trim();

    //prep
    let lines = csv.split('\n'),
        headers,
        output = [];

    //iterate over lines...
    lines.forEach((line, i) => {

        //...break line into tab-separated parts
        let parts = line.split(/\t+/);

        //...if not the headers line, push to output. By this time
       //we have the headers logged, so just match the value to
       //header of the same index
        if (i) {
            let obj = {};
            parts.forEach((part, i) => obj[headers[i]] = part);
            output.push(obj);

        //...else if headers line, log headers
        } else
            headers = parts;
    })

    //done
    console.log(output);
    return output;
}

CodePen。(注:在CodePen中,我从HTML div读取CSV,因此代码中存在微小差异。)

uklbhaso

uklbhaso3#

像这样的东西应该管用

function csvToJSON(csv) {
            var lines = csv.split("\n");
            var result = [];
            var headers = lines[0].split(",");

            lines.forEach( (line, index) => {
              if (index === 0) continue // skip the first line (headers)

              let data = {};
              let cells = line.split(",") // separate by commas
              cells.forEach( (cell, index) => {
                let header = headers[index];
                data[header] = cell;
              }
              result.push(data);
            }

            console.log(result);
            //console.log(JSON.stringify(result));

            return result;
        }
0tdrvxhp

0tdrvxhp4#

这就像一个魅力:上传〉转换〉复制https://csvjson.com/csv2json

watbbzwu

watbbzwu5#

let lines = string.split("\n");
let result = [];
let headers;
headers = lines[0].split(",");
for (let i = 1; i < lines.length; i++) {
    let obj = {};
    if(lines[i] == undefined || lines[i].trim() == "") {
        continue;
    }
    let words = lines[i].split(",");
    for (var j = 0; j < words.length; j++) {
        obj[headers[j].trim().replace(/(\r\n|\n|\r)/gm, "")] = 
        words[j].replace(/(\r\n|\n|\r)/gm, "");
        }
   result.push(obj);
   }
   console.log(result);

相关问题