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.

TypescriptSecurity Boundaries

Code

typescriptsnippet
24 lines
// 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

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`.