JavaScript 读写 JSON 文件实用指南**
在 Web 开发中,JSON(JavaScript Object Notation)因其轻量级、易读易写的特性,成为数据交换的主要格式之一,JavaScript 作为前端开发的核心语言,与 JSON 的交互尤为频繁,本文将详细介绍如何在 JavaScript 中读取和写入 JSON 文件,涵盖浏览器端和 Node.js 环境下的不同方法。
读取 JSON 文件
读取 JSON 文件的方式取决于 JavaScript 的运行环境:浏览器端或 Node.js 服务端。
浏览器端读取 JSON 文件
在浏览器端,由于安全限制(同源策略),JavaScript 不能直接读取本地文件系统中的 JSON 文件,除非通过用户交互(如文件输入选择)或加载来自同源服务器的 JSON 文件。
通过 fetch API 加载服务器上的 JSON 文件(推荐)
这是现代浏览器中获取远程 JSON 数据的标准方式,JSON 文件托管在你的服务器上,可以通过 fetch 请求获取。
// 假设有一个名为 data.json 的文件位于服务器的 /data/ 目录下
fetch('/data/data.json')
.then(response => {
// 检查响应是否成功
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
// 将响应体解析为 JSON 对象
return response.json();
})
.then(data => {
// 在这里处理获取到的 JSON 数据
console.log('成功读取 JSON 数据:', data);
// 操作 DOM 或进行其他数据处理
})
.catch(error => {
// 处理请求过程中可能出现的错误
console.error('读取 JSON 文件时出错:', error);
});
通过 XMLHttpRequest 加载 JSON 文件(较传统)
XMLHttpRequest 是较老的 API,但仍然可用,尤其是在需要支持非常老的浏览器时。
var xhr = new XMLHttpRequest();
xhr.open('GET', '/data/data.json', true);
xhr.responseType = 'json'; // 自动解析响应为 JSON
xhr.onload = function() {
if (xhr.status === 200) {
var data = xhr.response;
console.log('成功读取 JSON 数据:', data);
} else {
console.error('读取 JSON 文件时出错,状态码:', xhr.status);
}
};
xhr.onerror = function() {
console.error('请求 JSON 文件时发生网络错误');
};
xhr.send();
通过文件输入控件读取本地 JSON 文件
如果需要让用户选择其本地计算机上的 JSON 文件进行读取,可以使用 <input type="file"> 元素。
<input type="file" id="jsonFileInput" accept=".json">
<script>
document.getElementById('jsonFileInput').addEventListener('change', function(event) {
var file = event.target.files[0];
if (file) {
var reader = new FileReader();
reader.onload = function(e) {
try {
var data = JSON.parse(e.target.result);
console.log('成功读取本地 JSON 文件:', data);
} catch (error) {
console.error('解析 JSON 文件时出错:', error);
}
};
reader.readAsText(file);
}
});
</script>
Node.js 环境下读取 JSON 文件
在 Node.js 中,由于可以直接访问文件系统,读取 JSON 文件非常简单,主要使用 fs (File System) 模块。
使用 fs.readFile (异步)
const fs = require('fs');
const path = require('path');
const jsonFilePath = path.join(__dirname, 'data.json'); // 假设 data.json 与脚本同目录
fs.readFile(jsonFilePath, 'utf8', (err, data) => {
if (err) {
console.error('读取 JSON 文件时出错:', err);
return;
}
try {
const jsonData = JSON.parse(data);
console.log('成功读取 JSON 数据:', jsonData);
} catch (parseErr) {
console.error('解析 JSON 数据时出错:', parseErr);
}
});
使用 fs.readFileSync (同步)
如果需要在读取文件后立即执行后续操作,可以使用同步方法。
const fs = require('fs');
const path = require('path');
const jsonFilePath = path.join(__dirname, 'data.json');
try {
const data = fs.readFileSync(jsonFilePath, 'utf8');
const jsonData = JSON.parse(data);
console.log('成功读取 JSON 数据:', jsonData);
} catch (err) {
console.error('读取或解析 JSON 文件时出错:', err);
}
使用 fs.promises (Promise 风格异步 - 推荐)
Node.js 的 fs 模块提供了 promises API,可以使用 async/await 语法,使异步代码更易读。
const fs = require('fs').promises;
const path = require('path');
async function readJsonFile() {
const jsonFilePath = path.join(__dirname, 'data.json');
try {
const data = await fs.readFile(jsonFilePath, 'utf8');
const jsonData = JSON.parse(data);
console.log('成功读取 JSON 数据:', jsonData);
return jsonData;
} catch (err) {
console.error('读取或解析 JSON 文件时出错:', err);
throw err; // 可以选择重新抛出或处理错误
}
}
readJsonFile();
写入 JSON 文件
同样,写入 JSON 文件也分为浏览器端和 Node.js 环境。
浏览器端写入 JSON 文件
浏览器端出于安全考虑,不能直接将数据写入到用户的本地文件系统的任意位置,通常需要通过以下方式:
方法:使用 Blob 和 URL.createObjectURL 下载 JSON 文件
这是浏览器端“写入” JSON 文件的常用方式,实际上是生成一个下载链接,让用户保存文件。
const dataToWrite = {
name: "张三",
age: 30,
city: "北京"
};
// 将 JavaScript 对象转换为 JSON 字符串
const jsonString = JSON.stringify(dataToWrite, null, 2); // null, 2 表示格式化,缩进2个空格
// 创建 Blob 对象
const blob = new Blob([jsonString], { type: 'application/json' });
// 创建下载链接
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'data.json'; // 指定下载的文件名
// 触发下载
document.body.appendChild(a);
a.click();
// 清理
document.body.removeChild(a);
URL.revokeObjectURL(url); // 释放 URL 对象
Node.js 环境下写入 JSON 文件
在 Node.js 中,使用 fs 模块可以轻松地将 JSON 数据写入文件。
使用 fs.writeFile (异步)
const fs = require('fs');
const path = require('path');
const dataToWrite = {
name: "李四",
age: 25,
city: "上海"
};
const jsonFilePath = path.join(__dirname, 'output.json');
const jsonString = JSON.stringify(dataToWrite, null, 2);
fs.writeFile(jsonFilePath, jsonString, 'utf8', (err) => {
if (err) {
console.error('写入 JSON 文件时出错:', err);
return;
}
console.log('JSON 文件写入成功:', jsonFilePath);
});
使用 fs.writeFileSync (同步)
const fs = require('fs');
const path = require('path');
const dataToWrite = {
name: "王五",
age: 28,
city: "广州"
};
const jsonFilePath = path.join(__dirname, 'output_sync.json');
const jsonString = JSON.stringify(dataToWrite, null, 2);
try {
fs.writeFileSync(jsonFilePath, jsonString, 'utf8');
console.log('JSON 文件写入成功:', jsonFilePath);
} catch (err) {
console.error('写入 JSON 文件时出错:', err);
}
使用 fs.promises.writeFile (Promise 风格异步 - 推荐)
const fs = require('fs').promises;
const path = require('path');
async function writeJsonFile() {
const dataToWrite = {
name: "赵六",
age: 35,
city: "深圳"
};
const jsonFilePath = path.join(__dirname, 'output_promise.json');
const jsonString = JSON.stringify(dataToWrite, null, 2);
try {
await fs.writeFile(jsonFilePath, jsonString, 'utf8');
console.log('JSON 文件写入成功:', jsonFilePath);
} catch (err) {
console.error('写入 JSON 文件时出错:', err);
}
}
writeJsonFile();
注意事项
- JSON 格式有效性:在写入 JSON 文件前,确保要写入的数据是有效的 JavaScript



还没有评论,来说两句吧...