JSON limitations
Learn JSON limits, such as how it handles undefined, Date and functions.
Values that get lost
This format does not support every JavaScript value. When you turn an object into text, properties holding undefined, functions and Symbol are silently dropped; they do not appear in the result.
const obj = { name: 'Alex', skip: undefined };
const text = stringify(obj);
// text === '{"name": "Alex"}'So when you parse the text back, these properties are gone. Store important data by converting it to another type first.
Dates become strings
When you turn a Date object into text, the result is a string: the international format of the date. When you parse it back, you get a string, not a Date object.
const obj = { created: new Date() };
const text = stringify(obj);
const back = parse(text);
// back.created is a string, not a DateTo restore the date, convert it back with new Date(back.created).
Exercise See the function loss
Turn the widget object into text and assign it to text. Notice that the onClick function is not in the text.
Show example solution
Call stringify with widget.
Example solution:
const text = stringify(widget);
Test yourself
-
What happens after stringify?
stringify({a: 1, b: undefined})- a is dropped
- both are dropped
- b is dropped, a stays
- both stay
Show answer
b is dropped, a stays — Correct! undefined properties are dropped; numbers stay.
-
Match the limitation
- undefined
- dropped
- Date
- becomes string
- function
- lost
- number
- kept
-
What happens when a Date is parsed back?
parse(stringify({d: new Date(0)}))- A Date object returns
- null returns
- It throws
- A string returns
Show answer
A string returns — Correct! A Date becomes a string; parsing back keeps it a string.