Convert JSON to CSV with json2csv [JavaScript/Node.js]

Tadashi Shigeoka ·  Thu, May 16, 2019

I’ll introduce JavaScript sample code for converting JSON to CSV using the npm package json2csv.

npm

Convenient Features of json2csv

Personally, I find these two points particularly convenient:

  • You can quickly convert JSON to CSV without struggling with loop processing
  • You can customize field names that correspond to headers
  • The unwind option expands arrays for you

Usage Examples of json2csv

Example) Header Customization

json2csv#example-3

const { Parser } = require('json2csv');

const fields = [{
  label: 'Car Name',
  value: 'car'
},{
  label: 'Price USD',
  value: 'price'
}];

const json2csvParser = new Parser({ fields });
const csv = json2csvParser.parse(myCars);

console.log(csv);

Example) Array Expansion with unwind Option

json2csv#example-7

const { Parser } = require('json2csv');

const fields = ['carModel', 'price', 'colors'];
const myCars = [
  {
    "carModel": "Audi",
    "price": 0,
    "colors": ["blue","green","yellow"]
  }, {
    "carModel": "BMW",
    "price": 15000,
    "colors": ["red","blue"]
  }, {
    "carModel": "Mercedes",
    "price": 20000,
    "colors": "yellow"
  }, {
    "carModel": "Porsche",
    "price": 30000,
    "colors": ["green","teal","aqua"]
  }
];

const json2csvParser = new Parser({ fields, unwind: 'colors' });
const csv = json2csvParser.parse(myCars);

console.log(csv);

Execution result:

"carModel","price","colors"
"Audi",0,"blue"
"Audi",0,"green"
"Audi",0,"yellow"
"BMW",15000,"red"
"BMW",15000,"blue"
"Mercedes",20000,"yellow"
"Porsche",30000,"green"
"Porsche",30000,"teal"
"Porsche",30000,"aqua"

That’s all from the Gemba, where we want to quickly convert JSON to CSV with json2csv.