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 - https://www.npmjs.com/package/json2csv
# 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.
Like this:
Like Loading...