Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 6.6 — JSON
JavaScript · Example 3 of 4

Pretty printing, replacer and reviver

The array replacer kept two keys. The function replacer dropped cardNumber, and 2 indented the result (see the page). The reviver turned the date string back into a Date.

JSON is a text format for data that looks like JavaScript objects; JSON.stringify turns values into JSON text and JSON.parse turns the text back into values, with rules about what survives, plus options for pretty printing and for filtering or reviving values.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Stringify { title: "Notes", pages: 40, draft: undefined } with two-space indentation and log it. Which key is missing and why?

02

Write safeParse(text, fallback) that returns the parsed value, or fallback if the text isn't valid JSON. Test it with '[1,2]' and '[1,2'.

03

Stringify { user: "asha", password: "secret", token: "abc" } so that password and token are written as "***".

Explain it without notes

01

What is JSON, and how is it different from a JavaScript object literal?

02

What happens to undefined, functions, NaN, Date, Map and BigInt in JSON.stringify?

03

How do the replacer and reviver arguments work? Give a use for each.

04

How should you safely read JSON from localStorage or an API?

Pretty printing, replacer and reviver

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

{"id":42,"total":155}
5
true 10