1
0

More than 3 years have passed since last update.

yamlからjsonに変換してfor文で利用する(node.js)

Last updated at Posted at 2021-08-27

目的

  • yamlファイルを読み込んで、for文で処理するようなサンプルコードを作りたい。
  • Web上に自分の理想とするデータとコードのサンプルがなかったので、備忘的なサンプルコードを作りたい。

参考ページ

動作環境

$ node -v
v15.14.0

サンプルデータ

  • データとしては以下のような内容を扱います。
    • 単純な2次元配列です。
id name score
001 織田信長 100
002 豊臣秀吉 90
002 徳川家康 80

jsonデータをfor文で表示する

  • 上記のExcelのデータをjsonデータにして、for文で表示します。
  • 2パターン作りました。
  • 上記の参考ページのサンプルとは違って、jsonの2次元配列をネストせずに表現しているので、シンプルだと思います。
// パターン1 ... 連想配列の配列のパターン
var json_1 = [
  { id: "001", name: "織田信長", score: "100" },
  { id: "002", name: "豊臣秀吉", score: "90" },
  { id: "003", name: "徳川家康", score: "80" },
];

console.log(json_1);
for (var item_1 in json_1) {
  console.log(json_1[item_1]["id"]);
  console.log(json_1[item_1]["name"]);
}

console.log("=======================================");
// パターン2 ... 連想配列の配列にpersonsというkeyが付いているパターン
var json_2 = {
  persons: [
    { id: "001", name: "織田信長", score: "100" },
    { id: "002", name: "豊臣秀吉", score: "90" },
    { id: "003", name: "徳川家康", score: "80" },
  ],
};

console.log(json_2["persons"]);
for (var item_2 in json_2["persons"]) {
  console.log(json_2["persons"][item_2]["id"]);
  console.log(json_2["persons"][item_2]["name"]);
}
  • 実行結果は以下の通りです。
[
  { id: '001', name: '織田信長', score: '100' },
  { id: '002', name: '豊臣秀吉', score: '90' },
  { id: '003', name: '徳川家康', score: '80' }
]
001
織田信長
002
豊臣秀吉
003
徳川家康
=======================================
[
  { id: '001', name: '織田信長', score: '100' },
  { id: '002', name: '豊臣秀吉', score: '90' },
  { id: '003', name: '徳川家康', score: '80' }
]
001
織田信長
002
豊臣秀吉
003
徳川家康

yamlデータをfor文で表示する

  • yamlデータをfor文で表示するためには、一度jsonに変換します。
  • 上記のExcelデータをyamlで書くと以下のようになります。
test.yaml
persons:
  - id: "001"
    name: "織田信長"
    score: 100
  - id: "002"
    name: "豊臣秀吉"
    score: 90
  - id: "003"
    name: "徳川家康"
    score: 80
  • personsという文字を省略することも出来ますが、yamlファイルの場合、通常はpersonsの部分はつけると思います。
  • そのため、yamlファイルをjsonファイルに変換する場合は、上記のパターン2 ... 連想配列の配列にpersonsというkeyが付いているパターンが該当します。
  • jsonからyamlに変換してfor文で表示するコードは以下のようになります。
// test.yamlを読み込んで、内容をfor文で表示します。

function loadYamlFile(filename) {
  const fs = require("fs");
  const yaml = require("js-yaml");
  const textYaml = fs.readFileSync(filename, "utf8");
  const textJson = JSON.stringify(yaml.safeLoad(textYaml), null, 0); // JSONに変換
  const objJson = JSON.parse(textJson);
  return objJson;
}

if (require.main === module) {
  const path = require("path");

  try {
    const objJson = loadYamlFile(path.join(__dirname, "./test.yaml"));
    console.log(objJson);
    console.log(objJson["persons"]);
    for (var item in objJson["persons"]) {
      console.log(objJson["persons"][item]["id"]);
      console.log(objJson["persons"][item]["name"]);
    }
  } catch (err) {
    console.error(err.message);
  }
}
  • 出力結果は以下の通りになります。
{
  persons: [
    { id: '001', name: '織田信長', score: 100 },
    { id: '002', name: '豊臣秀吉', score: 90 },
    { id: '003', name: '徳川家康', score: 80 }
  ]
}
[
  { id: '001', name: '織田信長', score: 100 },
  { id: '002', name: '豊臣秀吉', score: 90 },
  { id: '003', name: '徳川家康', score: 80 }
]
001
織田信長
002
豊臣秀吉
003
徳川家康

あとがき

  • 自分としては、これで満足です。
1
0
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
1
0