JSON - Node.js

fs.readFileSync を使ってJSONファイルを読み込む

jsonファイル - data.json

[
  { "en" : "apple", "ja" : "りんご"},
  { "en" : "orange", "ja" : "みかん"}
]

script.js

const fs = require('fs');

const data = JSON.parse(fs.readFileSync('./data.json', 'utf8'));

for (const key in data) {
    console.log(key, data[key]);
}

require を使ってJSONファイルを読み込む

jsonファイル - data.json

[
  { "en" : "apple", "ja" : "りんご"},
  { "en" : "orange", "ja" : "みかん"}
]

script.js

const data = require('./data.json');

for (const key in data) {
    console.log(key, data[key]);
}

読み込んだ JSON ファイルから新たな JSON ファイルを作成する

script.js

const fs = require('fs');
const data = JSON.parse(fs.readFileSync('./data.json', 'utf8'));
let num = data.length;
let arr = "[\n";
let que_name = "sym";
let ans_name = "name";
let file_name = "copy_data";

data.forEach((value, index) => {
  let txt = "";
  txt += "  { "
  txt += `"que" : "${value[que_name]}"`
  txt += `, "ans" : "${value[ans_name]}"`
  if(num == value["no"]){
    txt += " }\n"
  } else {
    txt += " },\n"
  }
  arr += txt;
})

arr += "]"

fs.writeFile(`./${file_name}.json`, arr, (err) => {});

data.json

[
  { "que" : "H", "ans" : "水素" },
  { "que" : "He", "ans" : "ヘリウム" },
  { "que" : "Li", "ans" : "リチウム" },
  { "que" : "Be", "ans" : "ベリリウム" }
] 

配列をJSON形式に整形

JSON.stringify() メソッドは、JavaScript のオブジェクトや値を JSON 文字列に変換します。

JSON.stringify(JSONオブジェクト, null, インデント数);
  • 第一引数:jsonオブジェクトを指定
  • 第二引数:コールバックを指定することができる
  • 第三引数:数値を指定すると、指定した数の空白文字をインデントして整形します。

配列を stringify を使ってそのまま実行すると以下のようになります。

const text = `line1
line2

line3

line4
line5`

const jsonText = JSON.stringify(text, null, 2);
console.log(jsonText)

// 結果
"line1\nline2\n\nline3\n\nline4\nline5"

改行コードで分割し、一度配列にしてから stringify を使うと以下のように整形できます。

const text = `line1
line2

line3

line4
line5`

const lines = text.split('\n');
const jsonText = JSON.stringify(lines, null, 2);
console.log(jsonText);

// 結果
[
  "line1",
  "line2",
  "",
  "line3",
  "",
  "line4",
  "line5"
]