catcopyJS enginenameagenameagetext · a string{"name":"Tom","age":3}{"name":"Tom","age":3}1const cat = { name: "Tom", age: 3 };2const text = JSON.stringify(cat);3console.log(text);4const copy = JSON.parse(text);5copy.age = 4;6console.log(cat.age, copy.age);cat.jsonConsole{"name":"Tom","age":3}cat.js:33 4cat.js:6"Tom"3text"Tom"3434
Back: the JavaScript engine and the objects cat and copy in memoryMiddle: the JSON text, and a file or the network; front: cat.js and the consoleTokens: instructions, the values "Tom", 3 and 4, and the text in an envelopeAt the back, the JavaScript engine and two objects in memory, cat and copy. In the middle, the JSON text on a strip, and a file or the network. In front, the script cat.js and the console. JSON.stringify writes the object cat out as text, piece by piece. Text can be saved or sent. JSON.parse reads the text and builds a new object, copy, that changes on its own. JSON is defined in ECMA-404 and RFC 8259. JavaScript's JSON.parse and JSON.stringify are defined in the ECMAScript specification (ECMA-262).

Data as text

  1. An object lives in a program's memory. To save it or send it to another program, it must become text. JSON, short for JavaScript Object Notation, is a simple text format for data that almost every language can read.

Object to text

Text to object

What happens

// step 1/9 · json
JSON     JavaScript Object Notation
is       plain text, written in a strict format
used to  save data in files (.json)
         send data between programs and computers
in JS    JSON.stringify  value → text
         JSON.parse      text  → value
standard ECMA-404, RFC 8259

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. The boxes in memory are a simplification: cat and copy are variables that each refer to an object; the objects hold the properties.