CSV for JSON in Typescript

I am trying to create a JSON file from data obtained from a CSV file loaded using file input.

I found many posts that do this in Javascript, but they just don't work for me in Typescript.

An error occurred while executing the code below - csv.Split is not a function, does anyone have any ideas how I can change my code to work.

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

component.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
}
+6
source share
2 answers

You pass a method Filein csvJSONinstead of a text file. You can use FileReaderto read its contents. Here is an example

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'>
Hide result
+3

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);
} 
}
0

Source: https://habr.com/ru/post/1015752/


All Articles