Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON to CSV file using json2csv nodejs

I newly learned node.js and I want to parse a JSON object to a CSV file using the json2csv node module. json2csv only support a flat structure where fields are direct children of the json root. I found how-to-parse-json-object-to-csv-file-using-json2csv-nodejs-module topic and changed createColumnContent function of json2csv to read object elemet of my json file. but my json file has array element and is something like this:

[
{
    "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"
        }
    ]
}

]

and I want something like that enter image description here

I call json2csv like this:

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

How can I read array and add to my csv file. thank you

like image 697
farhad Avatar asked Dec 14 '25 07:12

farhad


1 Answers

I just released a module that makes this process easy in 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);
});

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;

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

like image 112
Kauê Gimenes Avatar answered Dec 16 '25 19:12

Kauê Gimenes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!