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.
Code
// 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
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON Diff ViewerCompare two JSON documents and list every added, removed, and changed path in a structural diff, with clear before and after values.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.