【问题标题】:Csv to Json with nodeJS使用 nodeJS 将 Csv 转换为 Json
【发布时间】:2022-02-10 22:30:34
【问题描述】:

我想使用 csv-parser 库将 csv 文件转换为 json。

这是我的 csv 文件:

account/firstname,account/lastname,account/location/countryName,account/location/town,account/location/address,Id
Babouche,Dorian,US,Washington,***,1

这是我将 csv 转换为 json 的代码:

const csv = require('csv-parser');
const fs = require('fs');
let results = [];
let data;
fs.createReadStream('simple.csv')
    .pipe(csv())
    .on('data', (data) => results.push(data))
    .on('end', () => {
        data = JSON.stringify(results, null, 2)

        fs.writeFile('user.json', data, (err) => {
            if (err) {
                throw err;
            }
            console.log("JSON data is saved.");
        });
})

所需的 JSON:

[{
    account: {
        firstname: "Babouche",
        lastname: "Dorian",
        location: {
            countryName: "US",
            town: "Washington",
            address: "***"
        } 
    },
    Id: "1",
}
]

我得到的结果:

[
  {
    "account/firstname": "Babouche",
    "account/lastname": "Dorian",
    "account/location/countryName": "US",
    "account/location/town": "Washington",
    "account/location/address": "***",
    "Id": " 1"
  }
]

我想要一个关于如何轻松完成此任务的建议。

【问题讨论】:

    标签: node.js json csv


    【解决方案1】:

    我推荐使用'json-2-csv'

    首先,安装包

    npm install json-2-csv
    

    进口:

    let converter = require('json-2-csv');
    

    回调函数

    let csv2jsonCallback = function (err, json) {
        if (err) throw err;
            console.log(typeof json);
            console.log(json.length);
            console.log(json);
    }
    
    converter.csv2json(csv, csv2jsonCallback);
    

    承诺的功能

    converter.csv2jsonAsync(csv)
    .then(console.log)
    .catch((err) => console.log('ERROR: ' + err.message));
    

    【讨论】:

      猜你喜欢
      • 2015-12-20
      • 2019-10-11
      • 2015-08-23
      • 2016-08-03
      • 2019-02-16
      • 1970-01-01
      • 2018-01-04
      • 2021-08-29
      • 2023-04-02
      相关资源
      最近更新 更多