JSON.stringify Drops Undefined Fields

JSON.stringify silently drops undefined properties, functions, and symbols, and writes null for array slots, so round-trips lose those fields.

JavascriptData Integrity

Code

javascriptsnippet
20 lines
// JSON.stringify 静默丢弃 undefined 字段、函数与 symbol
const payload = {
  id: 7,
  note: undefined,
  retry: () => {},
  token: Symbol('secret'),
  tags: ['a', undefined, 'b'],
};

const json = JSON.stringify(payload);
console.log('stringified:', json);

// 还原后:丢掉的字段消失,数组空洞变成 null
const restored = JSON.parse(json);
console.log('restored keys:', Object.keys(restored));
console.log('array hole became:', restored.tags[1]);

// 同一个 undefined:数组保留槽位写 null,对象键整个消失
console.log('array keeps slot as null:', JSON.stringify(['x', undefined]));
console.log('object drops the key:', JSON.stringify({ value: undefined }));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

stringified: {"id":7,"tags":["a",null,"b"]}
restored keys: [ 'id', 'tags' ]
array hole became: null
array keeps slot as null: ["x",null]
object drops the key: {}

How it works

Top-level bindings payload, json, restored hold the demo state — nothing sits inside a function scope.

Applying it

The run emits 5 labeled sections — stringified:, restored keys:, array hole became:, array keeps slot as null:, object drops the key: — one per step.

Statements that matter

const json = JSON.stringify(payload);

Interactive Tools for This Topic

FAQ

Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. Its state lives in module-level bindings: `payload`, `json`, `restored`.