在 Node.js 中处理 JSON:从基础到进阶技术
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,已成为 Web API 和配置文件的实际标准。在 Node.js 中,JSON 处理内置于核心层面,使其处理快速且便捷。本文将全面解析 JSON 处理:从基础解析到使用流处理大文件。
基础:JSON.parse() 和 JSON.stringify()
两个全局方法——JSON.parse() 和 JSON.stringify()——是 JavaScript 中所有 JSON 处理的基础。
JSON.parse() — 将字符串转换为对象
JSON.parse() 方法接受一个 JSON 格式的字符串,并返回相应的 JavaScript 对象。如果字符串包含语法错误,将抛出 SyntaxError 异常。
const jsonString = '{"name": "安娜", "age": 30, "isAdmin": false}';const user = JSON.parse(jsonString);
console.log(user.name); // "安娜"console.log(user.age); // 30第二个可选参数是 reviver 函数,它允许在解析过程中转换值:
const jsonString = '{"date": "2024-01-15T10:30:00Z", "count": "42"}';const obj = JSON.parse(jsonString, (key, value) => { if (key === 'date') return new Date(value); if (key === 'count') return parseInt(value, 10); return value;});
console.log(obj.date instanceof Date); // trueconsole.log(typeof obj.count); // "number"JSON.stringify() — 将对象转换为字符串
JSON.stringify() 方法执行相反操作——将 JavaScript 对象转换为 JSON 字符串。它接受三个参数:值、替换函数(或键数组)以及用于格式化的空格数。
const user = { name: "伊万", age: 25, roles: ["admin", "editor"], metadata: null};
// 基本用法const json = JSON.stringify(user);console.log(json);// {"name":"伊万","age":25,"roles":["admin","editor"],"metadata":null}
// 带格式化的用法const prettyJson = JSON.stringify(user, null, 2);console.log(prettyJson);/*{ "name": "伊万", "age": 25, "roles": ["admin", "editor"], "metadata": null}*/替换函数允许过滤或转换值:
const user = { name: "彼得", password: "secret123", age: 28 };
const safeJson = JSON.stringify(user, (key, value) => { if (key === 'password') return undefined; // 删除密码 return value;});
console.log(safeJson); // {"name":"彼得","age":28}在 Node.js 中读写 JSON 文件
在实际项目中,JSON 数据通常存储在文件中。Node.js 提供了 fs(文件系统)模块用于文件系统操作。
从文件读取 JSON
const fs = require('fs');
// 同步读取try { const data = fs.readFileSync('config.json', 'utf8'); const config = JSON.parse(data); console.log(config.port); // 3000} catch (err) { console.error('读取文件错误:', err.message);}
// 异步读取(推荐)fs.readFile('config.json', 'utf8', (err, data) => { if (err) { console.error('错误:', err); return; } const config = JSON.parse(data); console.log(config);});将 JSON 写入文件
const fs = require('fs');
const settings = { theme: "dark", language: "zh", notifications: true};
// 带格式化的写入fs.writeFileSync('settings.json', JSON.stringify(settings, null, 2), 'utf8');console.log('settings.json 文件已创建');
// 异步写入fs.writeFile('settings.json', JSON.stringify(settings), (err) => { if (err) throw err;