我新学了node.js,我想使用json2csv节点模块将JSON对象解析为CSV文件。 json2csv仅支持平面结构,其中字段是json根的直接子级。我找到了how-to-parse-json-object-to-csv-file-using-json2csv-nodejs-module主题,并更改了json2csv的createColumnContent函数以读取我的json文件的对象要素。
但是我的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"
}
]
}
]
我想要这样的东西
我这样称呼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文件中。
谢谢
最佳答案
我刚刚发布了一个模块,可以在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