npm json2csv for converting JSON to CSV format is super convenient

Tadashi Shigeoka ·  Thu, April 5, 2018

The npm json2csv that nicely converts JSON to CSV format was convenient, so I’ll introduce it.

npm | エヌピーエム

Prerequisite) Don't output with arbitrary custom CSV

First, as a prerequisite, don’t output with arbitrary custom CSV.

For details, see So You Want to Write Your Own CSV Code? | POSTD.

console.log([ 'a', 'b', 'c' ].join(','));

If you’re thinking of outputting CSV with comma-separated values like this, definitely read the POSTD article.

How to use json2csv

Here’s sample code for json2csv using patterns I personally use often:

const Json2csvParser = require('json2csv').Parser;
const fields = ['jan', 'price', 'description'];

const products = [
  {
    "jan": "001",
    "name": "spam",
    "price": 1000,
    "description": "spam, spam"
  },
  {
    "jan": "102",
    "name": "hoge",
    "price": 2000,
    "description": "hoge\\" hoge"
  },
  {
    "jan": "203",
    "name": "fuga",
    "price": 3000,
    "description": "fuga fuga"
  },
];

const json2csvParser = new Json2csvParser({ fields, header: true });
const csv = json2csvParser.parse(products);

console.log(csv);

// Output result of console.log(csv) below
"jan","price","description"
"001",1000,"spam, spam"
"102",2000,"hoge"" hoge"
"203",3000,"fuga fuga"

// Delimiter is ,
// Strings are enclosed in "
// " is escaped
// Fields strings are output as headers in the first line (default true)
// "name" not included in fields is not output

That’s all from the Gemba where I wanted to nicely convert JSON to CSV format with Node.js.