我正在尝试从使用文件上传程序输入上传的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
}
3条答案
按热度按时间vxbzzdmp1#
您正在传递
File
给csvJSON
方法,而不是文件的文本。您可以使用FileReader
来读取其内容。第一个
agyaoht72#
下面是我在CSV到JSON上的完美工作。
Stackbliz Demo
联系人导入.组件.ts
联系人导入.组件.html
shyt4zoc3#
HTML格式
** typescript **