JSON.stringify Replacer And Reviver
Serialize an allow-list of fields with a JSON.stringify array replacer, indent output, and restore typed values on parse with a reviver.
Code
// JSON.stringify 的允许清单 replacer 与缩进;JSON.parse 的 reviver
const record = {
user: 'ada',
token: 'secret-token',
created: '2026-11-11T00:00:00Z',
};
// replacer 传数组:只序列化列出的键(token 被剔除)
const json = JSON.stringify(record, ['user', 'created'], 2);
console.log(json);
// reviver:反序列化时把 ISO 字符串还原成 Date
const parsed = JSON.parse(json, (key, value) =>
key === 'created' ? new Date(value) : value,
) as { user: string; created: Date };
console.log(parsed.user, parsed.created instanceof Date);
console.log(parsed.created.toISOString().slice(0, 10));
// replacer 传函数:返回 undefined 的键会被整体跳过
const masked = JSON.stringify({ a: 1, b: undefined }, (key, value) =>
typeof value === 'undefined' ? undefined : value,
);
console.log(masked);Output
Captured from a sandboxed run of this snippet in the build pipeline.
{
"user": "ada",
"created": "2026-11-11T00:00:00Z"
}
ada true
2026-11-11
{"a":1}What the code does
Everything operates on top-level bindings: record, json, parsed, masked.
The top-level object literal pins user, token, created as plain values — no derivation, no imports behind them.
Statements that matter
const masked = JSON.stringify({ a: 1, b: undefined }, (key, value) =>
typeof value === 'undefined' ? undefined : value,
);
const json = JSON.stringify(record, ['user', 'created'], 2);
const parsed = JSON.parse(json, (key, value) =>
key === 'created' ? new Date(value) : value,
) as { user: string; created: Date };
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
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. Its state lives in module-level bindings: `record`, `json`, `parsed`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.