Convert nested json to csv using node.js
I want to convert nested json to csv file using node.js. my JSON structure:
[
{
"Make": "Nissan",
"Model": "Murano",
"Year": "2013",
"Specifications": {
"Mileage": "7106",
"Trim": "SAWD"
},
"Items": [
{
"flavor": {
"name": "Cherry",
"id": 1
},
"packSize": {
"name": "200ML",
"id": 1
}
},
{
"flavor": {
"name": "Vanilla",
"id": 2
},
"packSize": {
"name": "300ML",
"id": 2
}
}
]
},
{
"Make": "BMW",
"Model": "X5",
"Year": "2014",
"Specifications": {
"Mileage": "3287",
"Trim": "M"
},
"Items": [
{
"flavor": {
"name": "Cherry",
"id": 1
},
"packSize": {
"name": "200ML",
"id": 1
}
},
{
"flavor": {
"name": "Vanilla",
"id": 2
},
"packSize": {
"name": "300ML",
"id": 2
}
}
]
}
]
I used the "json-2-csv" module, but it only converts a simple structure, not a nested structure. only "make", "model", "year" and "specification" are converted, "items" are not converted How to do this ???
+3
source to share
2 answers
You can use the module jsonexport
quite easily, check this example:
Here is the output using the json you provided and jsonexport:
Example:
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);
});
Output:
lastname;name;family.type;family.name;nickname;location
Smith;Bob;Father;Peter;;
David;James;Mother;Julie;;
Miller;Robert;;;;1231,3214,4214
Martin;David;;;dmartin;
+3
source to share