freecoding.school100% FREE · NO SIGNUP
Closure CavesISSUE #35 of 61

json · parse · stringify · replacer · reviver

LambdaVSThe Mutator
Lambda saysJSON.parse turns a JSON string into JS; JSON.stringify turns JS into a JSON string.

JSON is the data format of the web. JSON.parse(str) builds objects/arrays from text (throws on invalid JSON — wrap in try/catch). JSON.stringify(value, replacer, space) serializes; the third argument pretty-prints with indentation. JSON only covers data — functions, undefined, and dates don't round-trip cleanly.

Power-ups you unlock

The Mutator attacks — common mistakes

Boss battleStringify an object with 2-space indent, then parse it back.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>const obj={a:1,b:[2,3]}; const s=JSON.stringify(obj,null,2); const back=JSON.parse(s);
document.getElementById('o').textContent=s+'\nparsed.b[0]='+back.b[0];</script></body></html>
▶ Open the interactive comic issue
‹ Regex · Lookahead · LookbehindErrors · Try · Catch · Finally ›