javascriptで外部からデータをfetchで取り込む
jsonなどのデータを取り込んで処理していくのはfetch
<script>
fetch("sample.json")
.then( response => response.json() )
.then( data => {
for (const {key,value} of data) {
console.log(key + ":" + value);
}
});
// awaitを使った場合
async function myFetch() {
const response = await fetch("sample.json");
const data = await response.json();
for (const {key, value} of data) {
console.log(key + ":" + value)
}
}
myFetch()
</script>
sample.json
[
{"key": "apple", "value": "リンゴ" },
{"key": "orange", "value": "オレンジ" },
{"key": "melon", "value": "メロン" },
]