[英]How to convert csv file into json file using node js?
const fs = require('fs');
const csv =require('fast-csv');
const path= require('path');
fs.createReadStream('translation.csv')
.pipe(csv())
.on('data',function (data) {
console.log(data);
})
.on('end',function (data) {
console.log('data end');
})
This code read the csv file but I don't know who to convert into json file.Anyone please help me. 这段代码读取了csv文件,但我不知道谁可以将其转换为json文件。任何人都可以帮助我。
I don't know how fast-csv works but I assume that the first emitted data is headers, you'll want to reference those, probably something like 我不知道fast-csv的工作原理,但我假设首先发出的数据是标头,您可能想引用那些标头,例如
const items = [];
// ...
.on(data, data => items.push(data));
// ...
const headers = items.shift();
then you can use a simple algorithm like this 那么您可以使用这样的简单算法
// assuming data looks like so
const headers = ['a', 'b'];
const items = [[1, 2], [3, 4]];
const r = [];
for (let i = 0; i < items.length; i++) {
let obj = {};
let row = items[i];
for (let j = 0; j < row.length;j++) {
obj[headers[j]] = row[j];
}
r.push(obj);
}
console.log(r);
console.log(JSON.stringify(r));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.