掌握JSON序列化与反序列化的高级技巧,能有效处理复杂数据。1. 使用replacer函数可过滤敏感字段(如password)、转换日期为ISO格式,并预处理循环引用,避免序列化错误。2. reviver函数在反序列化时可自动将日期字符串还原为Date对象,或重建类实例,提升数据恢复精度。3. 针对循环引用,可通过WeakSet跟踪已见对象,返回“[Circular]”标识,防止JSON.stringify报错。4. 原生不支持Map、Set、Symbol和函数的序列化,但可用Array.from转换Map和Set,函数则通过字符串存储并谨慎使用eval还原。5. 自定义toJSON方法允许对象控制自身序列化行为,适合封装在类中,实现更内聚的数据输出逻辑。综合运用这些方法,可在保证安全与性能的前提下,扩展JSON处理能力,应对复杂场景。

JavaScript中的JSON序列化与反序列化不只是JSON.stringify()和JSON.parse()的简单调用。掌握一些高级技巧,能帮助你更灵活地处理复杂数据结构、避免常见陷阱,并提升性能和安全性。
1. 使用 replacer 函数精细控制序列化内容
在调用JSON.stringify()时,第二个参数可以传入一个replacer函数,用于决定哪些属性应该被序列化。
这个技巧特别适合过滤敏感字段或转换特定类型的数据。
排除某些字段:比如去掉对象中的password或token 转换日期:将Date对象转为ISO字符串 处理循环引用前的预处理示例:
const user = { name: "Alice", password: "secret123", lastLogin: new Date()};const json = JSON.stringify(user, (key, value) => { if (key === 'password') return undefined; // 过滤掉 if (value instanceof Date) return value.toISOString(); return value;});// 结果不包含 password,日期为标准格式
2. 利用 reviver 函数在反序列化时重建对象
JSON.parse()的第二个参数是reviver函数,可用于在解析过程中转换值。
立即学习“Java免费学习笔记(深入)”;
常用于将字符串化的日期自动还原为Date对象,或重构类实例。
示例:自动识别并恢复日期
const data = '{"name":"Bob","createdAt":"2023-08-15T10:00:00.000Z"}';const obj = JSON.parse(data, (key, value) => { if (typeof value === 'string' && /^d{4}-d{2}-d{2}Td{2}:d{2}:d{2}/.test(value)) { return new Date(value); } return value;});// obj.createdAt 是 Date 实例
3. 处理循环引用(Circular References)
默认情况下,包含循环引用的对象调用JSON.stringify()会抛出错误。
解决方法包括使用第三方库或自定义replacer来跳过重复引用。
手动处理循环引用的 replacer:
function getCircularReplacer() { const seen = new WeakSet(); return (key, value) => { if (typeof value === 'object' && value !== null) { if (seen.has(value)) { return '[Circular]'; } seen.add(value); } return value; };}const obj = { name: "John" };obj.self = obj;console.log(JSON.stringify(obj, getCircularReplacer())); // 输出:{"name":"John","self":"[Circular]"}
4. 序列化 Map、Set、Symbol 和函数的替代方案
原生 JSON 不支持 Map、Set、Symbol 和函数,但可以通过replacer和reviver模拟序列化。
Map 可转为数组对:Array.from(map) Set 可转为数组:Array.from(set) 函数可保存为字符串,在reviver中用eval或new Function还原(注意安全风险)示例:序列化 Map
const map = new Map([['a', 1], ['b', 2]]);const str = JSON.stringify(Array.from(map)); // "[["a",1],["b",2]]"// 反序列化const recovered = new Map(JSON.parse(str));
5. 自定义 toJSON 方法实现对象级控制
任何对象都可以定义toJSON()方法,该方法会在JSON.stringify()执行时被自动调用。
这比外部replacer更内聚,适合封装在类中。
示例:为类定制输出格式
class User { constructor(name, email, password) { this.name = name; this.email = email; this.password = password; } toJSON() { return { name: this.name, email: this.email, role: 'user' }; }}const user = new User("Tom", "tom@example.com", "pass");console.log(JSON.stringify(user)); // {"name":"Tom","email":"tom@example.com","role":"user"}
基本上就这些。合理使用 replacer、reviver 和 toJSON,再配合类型转换逻辑,就能应对大多数复杂场景。关键是理解 JSON 的边界,并在必要时扩展它的能力。
以上就是JavaScript中的JSON序列化与反序列化有哪些高级技巧?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/40029.html
微信扫一扫
支付宝扫一扫