2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Node.jsでCSVをJSONに変換する【csvtojson】

Last updated at Posted at 2023-11-20

csvtojsonというモジュールを使えばできるのだが、使い方について調べると古い情報が多かったり複雑なことをしていたりと、CSVをJSONに変換するというただそれだけのことの情報が見つからないので、備忘として残しておく。

やり方

CSVファイルを読み込んでJSONの配列にするモジュールなので、あとはそれを好きに修正してファイル出力すれば良い。

環境

version
Node.js 20.9.0
npm 10.0.0
csvtojson 2.0.10

コード(使用例)

// モジュール読み込み
const fs = require('fs');
const csv = require('csvtojson');

/* CSVをJSONに変換する関数 */
const csv2json = async (inputCsvPath, outputJsonPath) => {
  // CSVを配列として読み込み
  const jsonArray = await csv().fromFile(inputCsvPath);
  // ここで配列を加工してもOK
  // console.log(jsonArray);

  // 配列をJSONに変換
  const jsonIndent = 2;
  const jsonStr = JSON.stringify(jsonArray, undefined, jsonIndent);

  // ファイルに出力
  fs.writeFileSync(outputJsonPath, jsonStr);
}

/* メイン処理 */

// パス定義
const targetCsvPath = './target.csv';
const targetJsonPath = './output.json';

// 実行
csv2json(targetCsvPath, targetJsonPath);

実行例

上記のコードを実行するとこんな感じ

元となるCSV

1行目はヘッダー

target.csv
company,model
Apple,iPhone
BlackBerry,BlackBerry
Google,Pixel
kyocera,TORQUE
Samsung,Galaxy
SHARP,AQUOS
SONY,Xperia
Xiaomi,Redmi

出力JSON

CSVのヘッダーがJSONのkeyになる。

output.json
[
  {
    "company": "Apple",
    "model": "iPhone"
  },
  {
    "company": "BlackBerry",
    "model": "BlackBerry"
  },
  {
    "company": "Google",
    "model": "Pixel"
  },
  {
    "company": "kyocera",
    "model": "TORQUE"
  },
  {
    "company": "Samsung",
    "model": "Galaxy"
  },
  {
    "company": "SHARP",
    "model": "AQUOS"
  },
  {
    "company": "SONY",
    "model": "Xperia"
  },
  {
    "company": "Xiaomi",
    "model": "Redmi"
  }
]

おわりに

これからこのモジュールを使い始める方で同じ悩みを持っている方にこの記事が届きますように。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?