【问题标题】:How to convert parse line by line csv files to create one json file using nodejs?如何将逐行解析的 csv 文件转换为使用 nodejs 创建一个 json 文件?
【发布时间】:2020-07-31 03:30:54
【问题描述】:

基本上,我有 4 个 csv 文件,其中包含学生、他们的 ID、他们的成绩和课程。

我现在有

const fs = require('fs');
const path = require('path');
const csv = require('fast-csv');
const User = require('./models/user');

fs.createReadStream(path.resolve(__dirname, 'assets', 'users.csv'))
    .pipe(csv.parse({ headers: true }))
    // pipe the parsed input into a csv formatter
    .pipe(csv.format({ headers: true }))
    // Using the transform function from the formatting stream
    .transform((row, next) => {
        User.findById(row.id, (err, user) => {
            if (err) {
                return next(err);
            }
            return next(null, {
                id: row.id,
                name: row.name,
                email: row.email,
                country: row.country,
                age: row.age,
                totalAverage: row.totalAverage,

            });
        });
    })
    .pipe(process.stdout)
    .on('end', () => process.exit());

使用fast-csv,这只是逐行读取并逐行打印每列数据。我不知道将每个学生存储在一个数组列表中并将他们的数据和课程存储在其中是否更好。然后,写入一个 json。

【问题讨论】:

    标签: node.js json csv parsing


    【解决方案1】:

    我认为将它们存储在一个数组中会很好,我们可以在.on('end')处理程序中处理它们。

    【讨论】:

      猜你喜欢
      • 2015-10-18
      • 1970-01-01
      • 1970-01-01
      • 2012-10-25
      • 1970-01-01
      • 2022-01-18
      • 2014-01-04
      • 2013-07-23
      • 1970-01-01
      相关资源
      最近更新 更多