JSON Replacer And Reviver Reshape Payloads
Scrub payloads on serialize with a JSON.stringify replacer and rebuild types on parse with a reviver — tokens redacted per key, date strings revived as Date.
Code
// 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));Output
Captured from a sandboxed run of this snippet in the build pipeline.
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
]
}What the code does
Module-level bindings hold the data — payload, safe, stored, back — with no function scope in between.
Using it
Running the file prints labeled results such as safe:, revived:, roundtrip n: — each operation’s effect is visible in the output.
Key statements
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 });
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. Its state lives in module-level bindings: `payload`, `safe`, `stored`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.