NodeJs : Convert json to csv using node module

Its very common usecase to convert json docs or Mongo doucments into csv and share with other. I am sharing a simple node module with example to accomplish the same.

Details of package -

# To install node module from cmd 
npm install json2csv --save

# create a converter.js javascript file as below with you input json and mapping.

var json2csv = require('json2csv');
var fs = require('fs');
var fields = ['car.make', 'car.model', 'price', 'color'];
var myCars = [

        "car": {
            "make": "Hundai", "model": "sonata"
        "price": 30000,
        "color": "white"
        "car": {
            "make": "Audi", "model": "A3"
        "price": 40000,
        "color": "blue"
    }, {
        "car": {"make": "BMW", "model": "F20"},
        "price": 35000,
        "color": "black"
    }, {
        "car": {"make": "Porsche", "model": "9PA AF1"},
        "price": 60000,
        "color": "green"
var csv = json2csv({ data: myCars, fields: fields });

fs.writeFile('file.csv', csv, function(err) {
if (err) throw err;
console.log('file saved');

# now run javascript file on node
node converter.js

# This will create a csv file in the current directory called as file.csv open it in excell and you are done.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s