在Typescript中使用CSV到JSON

Tob*_*son 9 csv json file typescript angular

我正在尝试根据从使用文件上载器输入上载的CSV文件接收的数据创建JSON文件.

我发现很多帖子在Javascript中这样做,但他们在Typescript中并不适合我.

我运行下面的代码时得到的错误是csv.Split不是一个函数,有没有人有任何想法如何我可以改变我的代码工作.

如果您需要更多信息,请提前告知我们.

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
}
Run Code Online (Sandbox Code Playgroud)

Ale*_* L. 10

您将传递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]);
};
Run Code Online (Sandbox Code Playgroud)
<input type='file' onchange='convertFile(event)' id='fileInput'>
Run Code Online (Sandbox Code Playgroud)


Sai*_*rya 5

这是我在 CSV 到 JSON 方面的工作,效果非常好。

Stackbliz 演示

contact-imports.component.ts

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-contact-imports',
  templateUrl: './contact-imports.component.html',
  styleUrls: ['./contact-imports.component.scss']
})


export class ContactImportsComponent implements OnInit {

  csvContent: string;
  contacts: Array<any> = [];
  properties:any = "";
  flag:boolean = false;
  constructor( private toastr: ToastrService) { }
  ngOnInit() {
    
  }

  
  onFileLoad(fileLoadedEvent) {
    const textFromFileLoaded = fileLoadedEvent.target.result;
    this.csvContent = textFromFileLoaded;

    //Flag is for extracting first line
    let flag = false;
    // Main Data
    let objarray: Array<any> = [];
    //Properties
    let prop: Array<any> = [];
    //Total Length
    let size: any = 0;

    for (const line of this.csvContent.split(/[\r\n]+/)) {

      if (flag) {

        let obj = {};
        for (let k = 0; k < size; k++) {
          //Dynamic Object Properties
          obj[prop[k]] = line.split(',')[k]
        }
        objarray.push(obj);

      } else {
        //First Line of CSV will be having Properties
        for (let k = 0; k < line.split(',').length; k++) {
          size = line.split(',').length;
          //Removing all the spaces to make them usefull, also removing any " characters 
          prop.push(line.split(',')[k].replace(/ /g, '').replace(/"/g, ""));
        }
        flag = true;
      }
    }
    this.contacts = objarray;
    this.properties = [];
  
    this.properties = prop;
    console.log(this.properties);
    console.log(this.contacts);
    this.flag = true;
  

    // console.log(this.csvContent);
  }




  onFileSelect(input: HTMLInputElement) {

    const files = input.files;
    var fileTypes = ['csv'];  //acceptable file types

    if (files && files.length) {
      var extension = input.files[0].name.split('.').pop().toLowerCase(),  //file extension from input file
      isSuccess = fileTypes.indexOf(extension) > -1;  //is extension in acceptable types
       //console.log(isSuccess);
      //  console.log("Filename: " + files[0].name);
      // console.log("Type: " + files[0].type);
      //  console.log("Size: " + files[0].size + " bytes");
      if(isSuccess){
        const fileToRead = files[0];

        const fileReader = new FileReader();
        fileReader.onload = this.onFileLoad;
  
  
        fileReader.readAsText(fileToRead, "UTF-8");
      }else{
        this.toastr.error("Invalid File Type", 'Failed');
      }

    
    }

  }
}
Run Code Online (Sandbox Code Playgroud)

contact-imports.component.html

 <div class="container-fluid">
      <div class="col-md-6">
          <img src="https://img.icons8.com/color/48/000000/csv.png"/> 
          <span class="text-muted" style="font-size: 22px;">Import Contacts From CSV</span>
        
     
          <div class="form-group">
                 <input class="form-control" accept=".csv" id="csv" type="file" (change)="onFileSelect($event.target)" name="myfile">
            </div>
      </div> 
    

  </div>
Run Code Online (Sandbox Code Playgroud)