JavaScript Tutorial: JSON
JSON.parse, JSON.stringify, replacers, revivers, custom serialization, and handling every edge case.
The language of APIs
JSON is how JavaScript objects travel across the internet. Nearly every API request and response is JSON. It looks like JavaScript object literals — but it's stricter, and there are important differences.
After this chapter, you'll never be surprised by a JSON quirk again.
What you'll learn in this JavaScript json tutorial
This interactive JavaScript tutorial has 8 hands-on exercises. Estimated time: 18 minutes.
- JSON.stringify — object to string — `JSON.stringify(value)` converts a JavaScript value to a JSON string.
- JSON.stringify with indent — The second and third arguments to `JSON.stringify`:
- JSON.parse — string to object — `JSON.parse(str)` converts a JSON string back to a JavaScript value.
- Replacer — filter and transform — The `replacer` argument controls what gets serialized:
- Reviver — transform on parse — `JSON.parse(str, reviver)` lets you transform values while parsing.
- Custom toJSON method — When a class has a `toJSON()` method, `JSON.stringify` uses its return value instead of the raw object.
- Handling circular references — Objects that reference themselves crash `JSON.stringify` with `TypeError: circular structure`.
- Build a data serialiser — Final challenge — no starter code.
JavaScript JSON concepts covered
- The language of APIs