gotchajavascriptMajor
JSON.stringify silently drops undefined, functions, and symbols
Viewed 0 times
JSON.stringifyundefined droppeddata lossserializationNaN null
Error Messages
Problem
JSON.stringify() silently removes properties with undefined values, function values, and Symbol values. It also converts NaN and Infinity to null. This causes silent data loss when serializing objects.
Solution
Be aware of what's dropped and handle it:
const obj = {
a: 1,
b: undefined, // DROPPED
c: function(){}, // DROPPED
d: Symbol(), // DROPPED
e: NaN, // becomes null
f: Infinity, // becomes null
};
JSON.stringify(obj) // {"a":1,"e":null,"f":null}
// Use a replacer to preserve values
JSON.stringify(obj, (key, value) => {
if (value === undefined) return '__undefined__';
if (typeof value === 'function') return '__function__';
if (Number.isNaN(value)) return '__NaN__';
return value;
});
// For Maps/Sets, convert first
const mapObj = Object.fromEntries(myMap);
const setArr = [...mySet];
const obj = {
a: 1,
b: undefined, // DROPPED
c: function(){}, // DROPPED
d: Symbol(), // DROPPED
e: NaN, // becomes null
f: Infinity, // becomes null
};
JSON.stringify(obj) // {"a":1,"e":null,"f":null}
// Use a replacer to preserve values
JSON.stringify(obj, (key, value) => {
if (value === undefined) return '__undefined__';
if (typeof value === 'function') return '__function__';
if (Number.isNaN(value)) return '__NaN__';
return value;
});
// For Maps/Sets, convert first
const mapObj = Object.fromEntries(myMap);
const setArr = [...mySet];
Why
JSON is a data interchange format that only supports strings, numbers, booleans, null, objects, and arrays. JavaScript has more types, so the extra ones are either dropped (undefined, functions, symbols) or converted to the closest JSON equivalent (NaN→null).
Gotchas
- In arrays, undefined becomes null (not removed): [1, undefined, 3] → [1, null, 3]
- toJSON() method on objects is called automatically by JSON.stringify
- BigInt throws TypeError — it's not silently converted
- Circular references throw TypeError — use a replacer to handle them
Code Snippets
JSON.stringify data loss
const data = { a: 1, b: undefined, c: NaN };
JSON.stringify(data) // '{"a":1,"c":null}' — b is GONE
// In arrays: undefined → null
JSON.stringify([1, undefined, 3]) // '[1,null,3]'Context
When serializing JavaScript objects to JSON for storage or transmission
Revisions (0)
No revisions yet.