目的
- yamlファイルを読み込んで、for文で処理するようなサンプルコードを作りたい。
- Web上に自分の理想とするデータとコードのサンプルがなかったので、備忘的なサンプルコードを作りたい。
参考ページ
-
忘れやすい、複雑なJSONの要素をfor...in文で取り出す方法
- 参考にはなりますが、自分の理想はネストがされていないjsonパターンを知りたいので、この記事を書きました。
動作環境
$ 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
徳川家康
あとがき
- 自分としては、これで満足です。