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);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http
.post('/api/TestConnection/TestConnection', jsonFile, options)
.subscribe(data => {
alert('ok');
}, 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 JSON.stringify(result);
}
source
share