← 中文资源

简体中文版本

JSON replacer 与 reviver 改写载荷

序列化时用 replacer 按键遮蔽 token(嵌套键同样被拦下),解析时用 reviver 把日期字符串复原成 Date 对象:JSON 一次往返进出各有钩子,缩进参数控制输出形态。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

safe: {"user":"ada","token":"[redacted]","nested":{"token":"[redacted]","ok":true}}
revived: true 2026-11-13T08:00:00.000Z
roundtrip n: 42
whitelist: {"user":"ada","nested":{}}
pretty:
{
  "a": 1,
  "b": [
    2,
    3
  ]
}

实现说明

演示用的数据放在这几个模块级绑定中:payload、safe、stored、back。

使用要点

  • 每一步打印都带着自己的标签:safe:、revived:、roundtrip n:。

常见问题

这段代码会引入外部包吗?

不涉及外部包,每个调用都落在内建 API 上。 文件用顶层绑定保存自己的状态:payload、safe、stored。

核心语句

const safe = JSON.stringify(payload, (key, value) => (key === 'token' ? '[redacted]' : value));
const back = JSON.parse(stored, (key, value) => (key === 'when' ? new Date(value) : value));
const stored = JSON.stringify({ when: '2026-11-13T08:00:00.000Z', n: 42 });

代码示例

// stringify 的 replacer:每个键值都会路过这个函数,适合按键脱敏
const payload = { user: 'ada', token: 's3cr3t', nested: { token: 'x9', ok: true } };
const safe = JSON.stringify(payload, (key, value) => (key === 'token' ? '[redacted]' : value));
console.log('safe:', safe);

// reviver:parse 时逐键复原——日期字符串变回 Date 对象
const stored = JSON.stringify({ when: '2026-11-13T08:00:00.000Z', n: 42 });
const back = JSON.parse(stored, (key, value) => (key === 'when' ? new Date(value) : value));
console.log('revived:', back.when instanceof Date, back.when.toISOString());
console.log('roundtrip n:', back.n);

// replacer 传数组时是白名单:只保留列出的键(未列出的嵌套键一并消失)
console.log('whitelist:', JSON.stringify(payload, ['user', 'nested']));

// 第三个参数控制缩进:2 空格便于人工阅读的输出形态
console.log('pretty:');
console.log(JSON.stringify({ a: 1, b: [2, 3] }, null, 2));