登录
首页 >  文章 >  前端

JSON序列化与反序列化高级技巧解析

时间:2026-04-08 15:48:13 219浏览 收藏

JSON序列化与反序列化远不止于基础的`stringify()`和`parse()`调用——通过灵活运用replacer函数过滤敏感字段、标准化日期、预处理循环引用,配合reviver函数智能还原Date对象或重建类实例,再结合WeakSet手动处理循环引用、Array.from转换Map/Set、自定义toJSON方法实现对象级序列化控制,你不仅能安全绕过原生JSON对函数、Symbol、循环结构等的限制,还能在复杂业务场景中兼顾数据完整性、安全性与性能,真正将JSON这一通用格式用得深入而精准。

JavaScript中的JSON序列化与反序列化有哪些高级技巧?

JavaScript中的JSON序列化与反序列化不只是JSON.stringify()JSON.parse()的简单调用。掌握一些高级技巧,能帮助你更灵活地处理复杂数据结构、避免常见陷阱,并提升性能和安全性。

1. 使用 replacer 函数精细控制序列化内容

在调用JSON.stringify()时,第二个参数可以传入一个replacer函数,用于决定哪些属性应该被序列化。

这个技巧特别适合过滤敏感字段或转换特定类型的数据。

  • 排除某些字段:比如去掉对象中的passwordtoken
  • 转换日期:将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函数,可用于在解析过程中转换值。

常用于将字符串化的日期自动还原为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}T\d{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 和函数,但可以通过replacerreviver模拟序列化。

  • Map 可转为数组对:Array.from(map)
  • Set 可转为数组:Array.from(set)
  • 函数可保存为字符串,在reviver中用evalnew 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 的边界,并在必要时扩展它的能力。

好了,本文到此结束,带大家了解了《JSON序列化与反序列化高级技巧解析》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多文章知识!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>