読み取るJSONファイル
data.json
[
{
"name": "Alice",
"age": 13,
"sex": "female"
},
{
"name": "Michel",
"age": 15,
"sex": "male"
}
]
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="main.js"></script>
<link rel="stylesheet" href="style.css">
<title>授業1012</title>
</head>
<body>
<table id="table">
</table>
</body>
</html>
style.css
table{
border-collapse: collapse;
}
table, th, td{
border: solid 1px #000;
}
th, td{
padding: 1em;
}
main.js
const url = "data.json";
function formatJSON(data){
console.log(data);
let tr = "<tr><th>名前</th><th>年齢</th><th>性別</th></tr>";
for(value of data){
tr += "<tr><td>" + value.name + "</td><td>" + value.age + "</td><td>"+ value.sex +"</td></tr>";
}
document.getElementById("table").innerHTML = tr;
}
window.addEventListener("load", ()=>{
fetch(url)
.then(response => response.json())
.then(data => formatJSON(data));
});
コメント