json2csv で JSON から CSV へ変換する [JavaScript/Node.js]

json2csv という npm で JSON から CSV へ変換する JavaScript サンプルコードをご紹介します。

npm

json2csv の便利な点

個人的に便利だなと思うのは以下の2点です。

  • ループ処理とかで頑張らずにサクッと JSON を CSV に変換できる
  • header に該当する field name をカスタマイズできる
  • unwind オプションが array を展開してくれる

json2csv の利用例

例) header のカスタマイズ

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

例) unwind オプションで array の展開

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

実行結果

"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"

以上、json2csv で JSON から CSV へサクッと変換したい、現場からお送りしました。