Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript中的CSV到JSON_Json_File_Csv_Angular_Typescript - Fatal编程技术网

Typescript中的CSV到JSON

Typescript中的CSV到JSON,json,file,csv,angular,typescript,Json,File,Csv,Angular,Typescript,我试图从使用文件上传器输入上传的CSV文件中接收的数据创建JSON文件 我发现很多帖子都是用Javascript写的,但它们在Typescript中对我来说不太合适 运行下面的代码时出现的错误是csv。Split不是一个函数,是否有人知道如何修改代码以使其正常工作 如果您需要更多信息,请提前告诉我,并表示感谢 组件。ts public testFile() { var file = (<HTMLInputElement>document.getElementById('fil

我试图从使用文件上传器输入上传的CSV文件中接收的数据创建JSON文件

我发现很多帖子都是用Javascript写的,但它们在Typescript中对我来说不太合适

运行下面的代码时出现的错误是csv。Split不是一个函数,是否有人知道如何修改代码以使其正常工作

如果您需要更多信息,请提前告诉我,并表示感谢

组件。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
}
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
          prop.push(line.split(',')[k].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');
      }

    
    }

  }
}
公共测试文件(){
var file=(document.getElementById('fileInput')).files[0];
var jsonFile=this.csvJSON(文件);
//设置Http POST选项
let headers=新的头({'Content-Type':'application/json'});
let options=newrequestoptions({headers:headers});
//使用测试连接数据调用Api
这是http
.post('/api/TestConnection/TestConnection',jsonFile,options)
.订阅(数据=>{
//警报请求正常
警报(“正常”);
},错误=>{
//日志错误
log(error.json());
});
}
公共csvJSON(csv){
变量行=csv.split(“\n”);
var结果=[];
var headers=行[0]。拆分(“”,“”);
对于(变量i=1;i
您正在将
文件
传递给
csvJSON
方法,而不是文件的文本。您可以使用
FileReader
读取其内容。这里有一个例子

const convertFile=()=>{
常量输入=document.getElementById('fileInput');
const reader=new FileReader();
reader.onload=()=>{
让text=reader.result;
console.log('CSV:',text.substring(01100)+'…');
//在此处将文本转换为json
//var json=this.csvJSON(文本);
};
reader.readAsText(input.files[0]);
};
HTML

>>>>>>>>”,行);
} 
}

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

联系人导入.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
}
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
          prop.push(line.split(',')[k].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');
      }

    
    }

  }
}
从'@angular/core'导入{Component,OnInit,ChangeDetectorRef};
从“ngx-toastr”导入{ToastrService};
@组成部分({
选择器:“应用程序联系人导入”,
templateUrl:“./contact imports.component.html”,
样式URL:['./联系导入.组件.scss']
})
导出类ContactImportComponent在NIT上实现{
csvContent:字符串;
联系人:数组=[];
属性:any=“”;
标志:布尔=假;
构造函数(私有toastr:ToastrService){}
恩戈尼尼特(){
}
onFileLoad(fileLoadedEvent){
const textFromFileLoaded=fileloadevent.target.result;
this.csvContent=textFromFileLoaded;
//标志用于提取第一行
让flag=false;
//主要数据
让objarray:Array=[];
//性质
让prop:Array=[];
//全长
let size:any=0;
对于(此.csvContent.split(/[\r\n]+/)的常量行){
国际单项体育联合会(旗){
设obj={};
for(设k=0;k-1;//扩展名是可接受的类型吗
//控制台日志(isSuccess);
//console.log(“文件名:”+文件[0].name);
//console.log(“类型:”+文件[0].Type);
//log(“大小:+文件[0]。大小+”字节”);
如果(isSuccess){
const fileToRead=文件[0];
const fileReader=new fileReader();
fileReader.onload=this.onFileLoad;
fileReader.readAsText(fileToRead,“UTF-8”);
}否则{
此.toastr.error(“无效文件类型”,“失败”);
}
}
}
}
联系人导入.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>

从CSV导入联系人

如果将数据从csv倒进哈希表(数组),不是更容易、更可读吗然后将其转换为json?肯定有更好的方法可以做到这一点,这正是我寻求建议的原因。好的,你从当前代码中得到了什么错误?csv.split不存在这一事实。你应该使用
FileReader.readAsText
读取文件,然后将其发送到
csvJSON
方法这不是给json对象它给出的只是一个普通数组