はじめに
今回は、配列内の連想配列のデータを取得する方法を書きます。
こちらのドキュメントを参考にしました。
https://developer.mozilla.org/ja/docs/Learn/JavaScript/Objects/JSON
サンプルデータ
こちらが今回のサンプルデータになります。
GitHub APIから取得したJSONデータになります。
"files": [
{
"sha": "aa8066a1fe98eb3f9436a30b4ff9c7300af8c0df",
"filename": "13.java/src/index.html",
"status": "modified",
"additions": 0,
"deletions": 1,
"changes": 1,
"blob_url": "https://github.com/hukuryo/hukuryo/blob/b6d6f503de6f1eeb340ac17e48f627e460d839cf/13.java%2Fsrc%2Findex.html",
"raw_url": "https://github.com/hukuryo/hukuryo/raw/b6d6f503de6f1eeb340ac17e48f627e460d839cf/13.java%2Fsrc%2Findex.html",
"contents_url": "https://api.github.com/repos/hukuryo/hukuryo/contents/13.java%2Fsrc%2Findex.html?ref=b6d6f503de6f1eeb340ac17e48f627e460d839cf",
"patch": "@@ -8,6 +8,5 @@\n </head>\r\n <body>\r\n <p>レビュー</p>\r\n- <p>newレビュー</p>\r\n </body>\r\n </html>\r"
}
]
今回はこのデータの中の、"filename"というカラムのデータを取得してみましょう。
取得するためのJavaScriptのコードはこちらです。
// データが格納されているエンドポイントのURLをfetchで取得する
fetch("https://api.github.com/repos/hukuryo/hukuryo/commits/b6d6f503de6f1eeb340ac17e48f627e460d839cf")
.then( response => response.json())
// 受け取ったJSONデータをdataという変数に格納
.then( data => {
// 配列の中の連想配列からデータを取り出す
console.log(data.files[0]['filename'])
});