Subham
Subham

Reputation: 1465

convert nested json to csv using node.js

I want to convert a 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 have used 'json-2-csv' module but it only converts the simple structure not the nested structure. only the 'make','model','year' and 'specification' is converted,'items' are not converted How to do this???

Upvotes: 5

Views: 10901

Answers (2)

Kauê Gimenes
Kauê Gimenes

Reputation: 1286

You can use the module jsonexport its pretty easy, check this sample:

Here is the output using the json you provided and jsonexport: enter image description here

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);
});

The ouput:

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

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

Upvotes: 7

B0ltz
B0ltz

Reputation: 425

Do you always have the same numbers of columns ? ie : Do you have a fixed (or max number) of items ?

Make;Model;Year;Mileage;Trim;Item_1_flavor_name;Item_1_packSize_name;Item_2_flavor_name;Item_2_packSize_name

Upvotes: 0

Related Questions