React で JSON をテーブルで表示してみます。
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>React Elements</title>
</head>
<body>
<div id="app"></div>
<br />
Mar/03/2022<br />
<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel" src="fetch_test.jsx" defer></script>
</body>
</html>
fetch_test.jsx
// -----------------------------------------------------------------------
//
// fetch_test.jsx
//
// Mar/03/2022
// -----------------------------------------------------------------------
const getCities = async() => {
// const url = 'http://localhost/tmp/json/tochigi.json'
const url = './tochigi.json'
const response = await fetch(url)
let text = await response.text()
// console.log(text)
const dict_aa = JSON.parse(text)
const Example = () =>
<table id='table_aa'>
<thead>
<tr><th>key</th>
<th>name</th>
<th>population</th>
<th>date_mod</th>
</tr>
</thead>
<tbody>
{
Object.entries(dict_aa)
.map( ([key, value]) =>
<tr key={key}><td>{key}</td>
<td>{value["name"]}</td>
<td>{value["population"]}</td>
<td>{value["date_mod"]}</td>
</tr> )
}
</tbody></table>
const app = document.getElementById('app')
const root = ReactDOM.createRoot(app)
root.render(<Example />)
}
// -----------------------------------------------------------------------
console.log("*** start ***")
getCities()
console.log("*** end ***")
// -----------------------------------------------------------------------
tochigi.json
{
"t0921": { "name": "宇都宮", "population": "34569", "date_mod": "2009-8-4" },
"t0922": { "name": "小山", "population": "17952", "date_mod": "2009-5-19" },
"t0923": { "name": "佐野", "population": "26929", "date_mod": "2009-3-28" },
"t0924": { "name": "足利", "population": "25197", "date_mod": "2009-12-21" },
"t0925": { "name": "日光", "population": "24976", "date_mod": "2009-11-25" },
"t0926": { "name": "下野", "population": "28945", "date_mod": "2009-1-26" }
}
ブラウザーで表示
本番で使う時は、コンパイルをする必要があります。
You are using the in-browser Babel transformer.
Be sure to precompile your scripts for production