使用JavaScript的Fetch API或FileReader来读取JSON文件并显示在网页上。
实现一个功能 ,用js对获取的json文件进行解析,并在web页面上显示出来。
方法1:使用Fetch API(适用于网络请求)
// 假设json文件位于同一目录下fetch('data.json').then(response => response.json()).then(data => {console.log(data); // 控制台输出数据document.body.innerHTML = `<pre>${JSON.stringify(data, null, 2)}</pre>`; // 渲染到网页}).catch(error => console.error('加载JSON失败:', error));
方法2:使用FileReader(适用于本地文件上传)
<input type="file" id="fileInput" accept=".json"><script>document.getElementById('fileInput').addEventListener('change', function(e) {const file = e.target.files[0];const reader = new FileReader();reader.onload = function(e) {const data = JSON.parse(e.target.result);console.log(data); // 控制台输出数据document.body.innerHTML += `<pre>${JSON.stringify(data, null, 2)}</pre>`;};reader.readAsText(file);});</script>
注意事项
- 跨域问题:如果使用fetch,JSON文件需与网页同域或配置CORS。
- 数据安全:本地文件上传方式需要用户主动选择文件。
- 格式化显示:JSON.stringify的第三个参数2表示缩进空格数,便于阅读。