一、上传JSON文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload Example</title>
</head>
<body>
<input type="file" id="json-file-input" accept=".json">
<p id="file-name"></p >
<script>
const fileInput = document.getElementById('json-file-input');
fileInput.addEventListener('change', function(event) {
const file = event.target.files[0];
if (file) {
const fileName = file.name;
document.getElementById('file-name').textContent = '选中的文件名: ' + fileName;
} else {
document.getElementById('file-name').textContent = '';
}
});
</script>
</body>
</html>
二、获取JSON文件内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Import JSON to LocalStorage</title>
</head>
<body>
<input type="file" id="json-file-input" accept=".json">
<button onclick="importJsonToLocalStorage()">导入JSON到LocalStorage</button>
<script>
function importJsonToLocalStorage() {
const fileInput = document.getElementById('json-file-input');
const file = fileInput.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(event) {
try {
const jsonData = JSON.parse(event.target.result);
const jsonString = JSON.stringify(jsonData);
localStorage.setItem('myJsonData', jsonString);
alert('JSON数据已成功保存到LocalStorage!');
} catch (error) {
alert('无法解析JSON文件或保存数据到LocalStorage!');
}
};
reader.readAsText(file);
} else {
alert('请选择一个JSON文件!');
}
}
</script>
</body>
</html>
三、导出JSON文件
let obj = {
name: 'John',
age: 30,
city: 'New York'
};
let json = JSON.stringify(obj);
let blob = new Blob([json], {type: 'application/json'});
let link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'data.json';
link.click();