Typescript 中的 CSV 到 JSON

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

CSV to JSON in Typescript

jsonfilecsvangulartypescript

提问by Toby Hymanson

I am trying to create a JSON file from the data received from a CSV file uploaded using a file uploader input.

我正在尝试从使用文件上传器输入上传的 CSV 文件接收的数据创建一个 JSON 文件。

I have found lots of posts doing this in Javascript but they just aren't quite working for me in Typescript.

我在 Javascript 中发现了很多这样的帖子,但它们在 Typescript 中对我来说不太适用。

The error I get when running the below code is csv.Split is not a function, does anyone have any ideas how I can alter my code to work.

运行以下代码时出现的错误是 csv.Split 不是函数,有没有人知道我如何更改代码以使其正常工作。

Let me know if you need more information and Thanks in advance.

如果您需要更多信息,请告诉我,并提前致谢。

component.ts

组件.ts

public testFile() {
    var file = (<HTMLInputElement>document.getElementById('fileInput')).files[0];        

    var jsonFile = this.csvJSON(file);


    // Set Http POST options
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    // Call Api with test connection data 
    this.http
        .post('/api/TestConnection/TestConnection', jsonFile, options)
        .subscribe(data => {
            // alert request ok
            alert('ok');
        }, error => {
            // Log error
            console.log(error.json());
        });
}

public csvJSON(csv) {
    var lines = csv.split("\n");

    var result = [];

    var headers = lines[0].split(",");

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

        var obj = {};
        var currentline = lines[i].split(",");

        for (var j = 0; j < headers.length; j++) {
            obj[headers[j]] = currentline[j];
        }

        result.push(obj);

    }

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

采纳答案by Aleksey L.

You are passing Fileto csvJSONmethod instead of file's text. You can use FileReaderto read its content. Here's an example

您正在传递FilecsvJSON方法而不是文件的文本。您可以使用FileReader阅读其内容。这是一个例子

const convertFile = () => {
  const input = document.getElementById('fileInput');

  const reader = new FileReader();
  reader.onload = () => {
    let text = reader.result;
    console.log('CSV: ', text.substring(0, 100) + '...');
    
    //convert text to json here
    //var json = this.csvJSON(text);
  };
  reader.readAsText(input.files[0]);
};
<input type='file' onchange='convertFile(event)' id='fileInput'>

回答by Mahendra Waykos

HTML

HTML

<input type="file" accept=".csv (change)="csv2Array($event)">

Typescript

打字稿

csv2Array(fileInput: any){
//read file from input
this.fileReaded = fileInput.target.files[0];

let reader: FileReader = new FileReader();
reader.readAsText(this.fileReaded);

 reader.onload = (e) => {
 let csv: string = reader.result;
 let allTextLines = csv.split(/\r|\n|\r/);
 let headers = allTextLines[0].split(',');
 let lines = [];

  for (let i = 0; i < allTextLines.length; i++) {
    // split content based on comma
    let data = allTextLines[i].split(',');
    if (data.length === headers.length) {
      let tarr = [];
      for (let j = 0; j < headers.length; j++) {
        tarr.push(data[j]);
      }

     // log each row to see output 
     console.log(tarr);
     lines.push(tarr);
  }
 }
 // all rows in the csv file 
 console.log(">>>>>>>>>>>>>>>>>", lines);
} 
}