JSON
An object only lives in a running program's memory. To save it in a file or send it to another computer, it has to become text, and JSON is the text format almost everyone uses. Follow a six-line script as JSON.stringify writes an object out as text, piece by piece, and JSON.parse reads that text back into a brand-new object.
5 quick questions
Pick an answer to see why. Your score saves with your progress.
01What does JSON.stringify({ name: "Tom", age: 3 }) return?
JSON.stringify writes the object as JSON text: keys and strings in double quotes, no spaces by default. The result is a string.
02After const copy = JSON.parse(text), is copy the same object as cat?
JSON.parse only sees characters. It builds a new object with the same properties, so copy === cat is false.
03The script sets copy.age = 4 and then runs console.log(cat.age, copy.age). What is printed?
copy is a separate object, so changing its age does not touch cat. The console prints 3 4.
04Which of these is valid JSON text?
JSON needs double quotes around every key and string and does not allow a trailing comma. JSON.parse throws a SyntaxError on the other three.
05Why do programs turn objects into JSON text at all?
Text can leave the program: be saved as a .json file or sent over the network, and any language can read it back.
Glossary
- JSON
- JavaScript Object Notation: a text format for data, with strict rules, that almost every programming language can read and write.
- Object
- A group of named values called properties, written with curly braces, such as { name: "Tom", age: 3 }.
- Property
- One named value inside an object, such as age with the value 3.
- String
- A piece of text: a sequence of characters. JSON text is stored in a string.
- JSON.stringify()
- Turns a value, such as an object, into a JSON string.
- JSON.parse()
- Reads a JSON string and builds a new value from it. It throws a SyntaxError if the text breaks JSON's rules.
- SyntaxError
- The error JavaScript throws when text is not written in the form it expects, for example JSON with single quotes.
Notes and sources
- JSON.stringify writes no spaces unless you ask: JSON.stringify(cat, null, 2) writes the same data over several lines, indented by two spaces. Both are valid JSON.
- JSON.stringify leaves out object properties whose value is a function, undefined or a symbol, and writes NaN and Infinity as null, because JSON has no way to write them.
- A JSON round trip is a common way to make a deep copy of plain data. It loses dates (they become strings), drops functions, and turns Maps and Sets into {}. structuredClone() copies dates, Maps and Sets correctly, though it cannot copy functions either.
- The boxes in memory are a simplification: cat and copy are variables that each refer to an object; the objects hold the properties.
- JSON is defined in ECMA-404 and RFC 8259. JavaScript's JSON.parse and JSON.stringify are defined in the ECMAScript specification (ECMA-262).
Quiz Unlocks after the last step.