node.js:将json数组转换为csv [英] node.js: Convert json array to csv
问题描述
我想在node.js中将元素的json数组转换为csv.我已经找到了执行此操作的模块,例如json2csv或json-csv,但它们并不完整.例如,json2csv仅支持平面结构,其中字段是json根的直接子级,并且所有json对象的架构都应该相同.
就我而言,我想要那个.
我想我有一个像这样的对象的json数组:
I want to convert a json array of elements to csv in node.js. I've found some module doing that like json2csv or json-csv but they are not complete. For example json2csv only support a flat structure where fields are direct children of the json root and also the schema should be the same for all json objects.
In my case, I want that.
I suppose that i've a json array of objects like that:
[{
"libelle" : "Projet 1",
"beneficiaire" : "Mr Leroy",
"nature" : "Diagnostics patrimoniaux",
"phasage" : "GLOBAL",
"budget": [
{"status": "BROUILLON"}
],
"status" : "BROUILLON"
},
{
"libelle" : "Projet 2",
"beneficiaire" : "Mr Leroy",
"nature" : "Diagnostics patrimoniaux",
"phasage" : "GLOBAL",
"status" : "BROUILLON"
}]
我想像这样将其转换为csv:
and i want to convert it to csv like that:
"libelle","beneficiaire","nature","phasage","budget[0].status","status"
"Projet 1","Mr Leroy","Diagnostics patrimoniaux","GLOBAL","BROUILLON","BROUILLON"
"Projet 2","Mr Leroy","Diagnostics patrimoniaux","GLOBAL",,"BROUILLON"
我正在寻找一个好的且完整的节点模块来实现这一目标.如果不存在,我会自己做.
I'm looking for a good and complete node module for doing that. If it doesn't exist, I will do it myself i think so.
推荐答案
您可以很容易地使用模块jsonexport
,请检查此示例:
You can use the module jsonexport
its pretty easy, check this sample:
示例:
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
Source: https://www.npmjs.com/package/jsonexport
这篇关于node.js:将json数组转换为csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!