HTML5 提供了 File API,允许网页读取用户选择的本地文件。读取本地 JSON 数据通常涉及以下几个步骤:
.json
文件。以下是一个简单的示例,展示如何使用 HTML5 和 JavaScript 读取本地 JSON 文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Read Local JSON</title>
</head>
<body>
<input type="file" id="jsonFile" accept=".json" />
<pre id="output"></pre>
<script>
document.getElementById('jsonFile').addEventListener('change', function(event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
try {
const data = JSON.parse(e.target.result);
document.getElementById('output').textContent = JSON.stringify(data, null, 2);
} catch (error) {
document.getElementById('output').textContent = 'Error parsing JSON: ' + error.message;
}
};
reader.readAsText(file);
}
});
</script>
</body>
</html>
通过上述步骤和代码示例,你可以有效地读取和处理本地 JSON 数据。如果遇到特定问题,可以根据错误信息进一步调试和解决。
领取专属 10元无门槛券
手把手带您无忧上云