64
55

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 3 years have passed since last update.

Node.jsでJSONを読み込んで加工して書き出す

Last updated at Posted at 2018-05-28

input.jsonを読み込んでoutput.jsonの形に整形して書き出すスクリプトです。
頻度は高くありませんが、ファイルを読み込んで何かをしたり、ファイルに書き出したりする場面があるので備忘録として残しておきます。

convert.js

const fs = require('fs');

const jsonObject = JSON.parse(fs.readFileSync('./input.json', 'utf8'));
const result = {};

jsonObject.list.forEach((obj) => {
    result[obj.id] = obj;
});

fs.writeFileSync('./output.json', JSON.stringify(result));
input.json

{
  "list": [
    {
      "id": "hoge",
      "name": "ほげ"
    },
    {
      "id": "fuga",
      "name": "ふが"
    }
  ]
}

output.json

{
  "hoge": {
    "id": "hoge",
    "name": "ほげ"
  },
  "fuga": {
    "id": "fuga",
    "name": "ふが"
  }
}
64
55
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
64
55

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?