JSON.stringify returns undefined — what to do
When and why JSON.stringify returns undefined instead of a string, and how to serialize undefined values, functions, and symbols the way you actually intended.
JSON.stringify(undefined) returns undefined (the JavaScript primitive), not the string "undefined". This surprises many developers and causes subtle bugs when the result is used as a response body, stored, or passed to JSON.parse.
When JSON.stringify returns undefined
- Top-level undefined:
JSON.stringify(undefined)→undefined - Top-level function:
JSON.stringify(() => {})→undefined - Top-level symbol:
JSON.stringify(Symbol('x'))→undefined
JSON.stringify(undefined) // undefined
JSON.stringify(() => {}) // undefined
JSON.stringify(Symbol('x')) // undefined
// Passing these results to JSON.parse:
JSON.parse(JSON.stringify(undefined))
// SyntaxError: Unexpected token u in JSON at position 0Properties silently dropped inside objects
Values that can't be serialized are dropped silently when they appear as object property values:
JSON.stringify({
name: "Ada",
fn: () => {}, // dropped
sym: Symbol('x'), // dropped
x: undefined, // dropped
})
// '{"name":"Ada"}'undefined in arrays becomes null
JSON.stringify([1, undefined, 3]) // '[1,null,3]' — undefined becomes null, not dropped
Fixes
Replace undefined with null before serializing
const value = someFunction() ?? null; // undefined → null JSON.stringify(value); // ✓ produces "null"
Use a replacer to control what's omitted
JSON.stringify(obj, (key, val) => val === undefined ? null : val); // converts all undefined values to null instead of dropping them
Use JSON.stringify with a fallback
const result = JSON.stringify(value) ?? '{"error":"not serializable"}';Checking before you parse
const raw = JSON.stringify(data);
if (raw === undefined) throw new Error('Data is not JSON-serializable');
sendToServer(raw);Paste your JSON into the validator →
Get the exact line, column, and a fix hint in seconds — no upload, no signup.
Open JSON Validator →