I am trying to create a JSON file from the data received from a CSV file uploaded using a file uploader input.
I have found lots of posts doing this in Javascript but they just aren't quite working for me in 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.
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
}
FileReader.readAsTextto read file and then send it tocsvJSONmethod