Command Palette

Search for a command to run...

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

Invalid JSON throws

Unquoted keys, single quotes, trailing commas and empty text are all invalid JSON. A bare number like 42 is valid. The exact message wording differs between browsers; this one is Chrome's.

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?

Invalid JSON throws

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

parsed: { ok: true }
bad JSON: SyntaxError
bad JSON: SyntaxError
bad JSON: SyntaxError
parsed: 42
Expected property name or '}' in JSON at position 1 (line 1 column 2)