我试图逐行将CSV对象转换为JSON对象。我不想将CSV文件转换为JSON,因为我的文件有超过400万个对象。
此外,我正在使用csvjson模块,但我认为您无法将CSV对象转换为JSON。我认为您只能将CSV文件转换为JSON
const lineReader = require('line-reader');
const csvjson = require("csvjson");
lineReader.eachLine('example.csv', function(line) {
const options = {
delimiter : ',' , // optional
quote : '"' // optional
};
let jsonObject= csvjson.toObject(line,options);
console.log(jsonObject) //prints []
});
答案 0 :(得分:0)
要逐行处理事物,在我看来您将需要一个不同的csv模块,该模块支持增量流解析并逐行输出实际的Javascript对象(您需要javascript对象,而不是JSON)。
NPM上有很多CSV模块,其中许多模块都具有一定级别的流支持。这个cvs-reader
似乎提供了正确的功能,并通过一个简单的演示程序为我工作。我确定还有其他具有类似功能的模块。
这是cvs-reader的工作演示。
const fs = require('fs');
const csvReader = require('csv-reader');
// All of these arguments are optional.
const options = {
skipEmptyLines: true,
asObject: true, // convert data to object
parseNumbers: true,
parseBooleans: true,
trim: true
};
const csvStream = new csvReader(options);
const readStream = fs.createReadStream('example.csv', 'utf8');
readStream.on('error', err => {
console.log(err);
csvStream.destroy(err);
}).pipe(csvStream).on('error', err => {
console.error(err);
}).on('data', (data) => {
// outputs an object containing a set of key/value pair representing a line found in the csv file.
console.log(data); // {firstname: "John", lastname: "Bundy", state: "CA"}
}).on('end', () => {
console.log('done');
});