实现说明
演示用的数据放在这几个模块级绑定中: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));