使用json2csv nodejs将JSON转换为CSV文件

时间:2015-01-05 15:00:46

标签: javascript json node.js csv

我新学习了node.js,我想使用json2csv节点模块将JSON对象解析为CSV文件。 json2csv仅支持平面结构,其中字段是json根的直接子节点。我找到了how-to-parse-json-object-to-csv-file-using-json2csv-nodejs-module主题并更改了json2csv的createColumnContent函数来读取我的json文件的对象elemet。 但我的json文件有数组元素,如下所示:

[
{
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": "10021"
    },
    "phoneNumber": [
        {
            "type": "home",
            "number": "212 555-1234"
        },
        {
            "type": "fax",
            "number": "646 555-4567"
        }
    ]
},
{
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": "10021"
    },
    "phoneNumber": [
        {
            "type": "home",
            "number": "212 555-1234"
        },
        {
            "type": "fax",
            "number": "646 555-4567"
        }
    ]
}

我想要那样的东西 enter image description here

我这样叫json2csv:

json2csv({
        data: body.issues, 
        fields: ['firstName','lastname','age','address.city', 'phoneNumber[?].type', 'phoneNumber[?].number']
    }, 
    function(err, csv) {
        if (err) console.log(err);
        fs.writeFile('sample.csv', csv, function(err) {
            if (err) throw err;
            console.log('file saved');
        });  
    }
);

如何读取数组并添加到我的csv文件中。 谢谢

2 个答案:

答案 0 :(得分:5)

我刚刚发布了一个模块,可以在Node.js中轻松完成此过程

var jsonexport = require('jsonexport');

var contacts = [{
   name: 'Bob',
   lastname: 'Smith',
   family: {
       name: 'Peter',
       type: 'Father'
   }
},{
   name: 'James',
   lastname: 'David',
   family:{
       name: 'Julie',
       type: 'Mother'
   }
},{
   name: 'Robert',
   lastname: 'Miller',
   family: null,
   location: [1231,3214,4214]
},{
   name: 'David',
   lastname: 'Martin',
   nickname: 'dmartin'
}];

jsonexport(contacts,function(err, csv){
    if(err) return console.log(err);
    console.log(csv);
});

输出:

lastname;name;family.type;family.name;nickname;location
Smith;Bob;Father;Peter;;
David;James;Mother;Julie;;
Miller;Robert;;;;1231,3214,4214
Martin;David;;;dmartin;

https://www.npmjs.com/package/jsonexport

答案 1 :(得分:2)

你可能最好自己转换数据,而不是覆盖json2csv包的一部分。然后,您可以将平面数据结构传递给json2csv进行格式化。

    var xform = [];
    for (var i=0, max=data.issuelinks.length; i<max; i++ ) {
            xform[xform.length] = { id:data.id, progress:data.progress.percent, issuelinkid:data.issuelinks[i].id, issuelinktypeid:data.issuelinks[i].type.id } 
    } 
    console.log(xform);