Learning object 48 of 100
JSON serialization laboratory
Serialize any value with JSON.stringify, parse it back with JSON.parse, and compare what went in with what came out.
Loading…
What it shows
JSON can represent objects, arrays, strings, finite numbers, booleans and null. Other values change on the way through: Dates become ISO strings, Map and Set become empty objects, undefined and functions are dropped from objects and become null inside arrays, NaN and Infinity become null, and BigInt makes stringify throw. Knowing this tells you what to convert before saving or sending data.
Guided experiment
- Pick
{ when: new Date(0) }. What type is when after the round trip? - Pick
[undefined, NaN, Infinity]and compare with{ a: undefined, f() {} }. - Try
{ big: 10n }. What happens?
Predict
What does JSON.stringify({ a: undefined, b: 1 }) produce?
Related
Lessons: Lesson 69: JSON serialization
Projects: Project 9: Shopping Cart Price Calculator
Source: web/assets/js/objects/object-048.js in the companion repository.