JSON.stringify()

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — Turning an Object Into Text

When your game saves a player's progress to a file or sends a Codémon to a server over the internet, it cannot send a live JavaScript object. Files and network messages can only carry plain text (strings). If you try to glue an object into a string directly, JavaScript does not write out its properties — it just turns it into useless placeholder text:

const zap = { name: "Zap", level: 4 }; console.log("Save file: " + zap);

To turn an object into real, usable text, JavaScript gives you `JSON.stringify()`. It takes any object or array and returns a string formatted in JSON — a universal text format understood by almost every programming language and server:

const zap = { name: "Zap", level: 4 }; const text = JSON.stringify(zap); console.log(text); console.log(typeof text);

Notice the two differences between the original object and the JSON string: 1. Every property key is wrapped in double quotes (`"name"`, `"level"`), with extra spaces removed. 2. The entire result has type `"string"`, ready to be saved to a file or sent across the network.

Exercise 2 — What JSON Looks Like

JSON stands for *JavaScript Object Notation*. It looks almost identical to the objects and arrays you already write in JavaScript, but it follows a few strict formatting rules: 1. Double quotes everywhere: Every object key (`"name"`) and every text string (`"Zap"`) must use double quotes — single quotes are never allowed in JSON. 2. Compact by default: `JSON.stringify()` removes spaces after colons and commas (`{"a":1}` instead of `{ a: 1 }`) so the text takes up as little space as possible. 3. Six basic value types: JSON supports strings (`"Zap"`), numbers (`42`), booleans (`true` / `false`), `null`, arrays (`[1,2]`), and objects (`{"a":1}`).

Because arrays and objects can be nested inside each other, `JSON.stringify()` can pack an entire trainer profile — including a full team of Codémon — into a single line of text:

const trainer = { name: "Sam", active: true, team: [ { name: "Zap", level: 4 }, { name: "Aquachu", level: 12 } ] }; console.log(JSON.stringify(trainer));

Exercise 3 — Making JSON Readable

A single-line JSON string is ideal for computers and network transfers, but hard for humans to read when an object gets large. If you pass two extra arguments — `null` followed by a number of spaces — `JSON.stringify()` formats the output across multiple lines with clean indentation:

const zap = { name: "Zap", level: 4, moves: ["Spark", "Thunder"] }; console.log(JSON.stringify(zap, null, 2));

Here is what each argument in `JSON.stringify(zap, null, 2)` does: 1. `zap` — the object or array you want to convert. 2. `null` — an optional filter slot (passing `null` keeps every property). 3. `2` — the number of spaces used to indent each nested level. Using `JSON.stringify(obj, null, 2)` is one of the handiest tricks for inspecting complex objects in the console.

Exercise 4 — Quiz: What Comes Out?

What does this code print?

const item = { name: "Potion", price: 30 }; console.log(JSON.stringify(item));
Options
• {"name":"Potion","price":30}
• { name: "Potion", price: 30 }
• [object Object]
• Potion, 30

Hint : JSON wraps every key in double quotes and removes the spaces.

Exercise 5 — Quiz: What Type?

What does this code print?

const text = JSON.stringify({ a: 1 }); console.log(typeof text);
Options
• "string"
• "object"
• "json"
• "undefined"

Hint : The whole point of the method is to produce text.

Exercise 6 — Save a Codémon

Turn the Codémon into a JSON string ready to be saved.

Hint : The tool lives on a built-in object, and its method name says it turns things into a string.

Exercise 7 — What Gets Left Out

JSON is strictly a data format — it only stores values, never code or behaviour. When `JSON.stringify()` converts an object, it silently drops two kinds of properties: 1. Functions (methods) stored inside the object. 2. Properties whose value is `undefined`.

const zap = { name: "Zap", level: 4, nickname: undefined, attack() { return "Spark!"; } }; console.log(JSON.stringify(zap));

Notice that no error is thrown: `nickname` and `attack` simply disappear from the JSON string, leaving only `name` and `level`. If you actually want an empty value to be preserved in JSON, use `null` instead of `undefined`.

Sets and Maps in JSON

JSON does not know about Set or Map either — stringifying them produces an empty `{}`. Convert them to arrays first (for example with `[...mySet]`) before calling `JSON.stringify()`.

Exercise 8 — Quiz: The Missing Method

What does this code print?

const cdm = { name: "Zap", roar() { return "Zap!"; } }; console.log(JSON.stringify(cdm));
Options
• {"name":"Zap"}
• {"name":"Zap","roar":"Zap!"}
• {"name":"Zap","roar":null}
• An error

Hint : JSON stores data only, never behaviour.

Exercise 9 — stringify Cheat Sheet

Match each expression with its result.

Items to match
• JSON.stringify({ a: 1 })
• JSON.stringify([1, 2])
• JSON.stringify(obj, null, 2)
• A function inside the object
Definitions
• {"a":1}
• [1,2]
• Indented, readable text
• Left out of the result

Exercise 10 — Save File Writer

Produce the save file for a trainer, in both the compact form used for storage and the readable form shown to the developer.

Step 1: `compact(trainer)` returns the single-line JSON of the trainer. Step 2: `pretty(trainer)` returns the JSON indented by 2 spaces. Step 3: print the compact version, then `"Size: N"` with its length in characters, then the pretty version. Step 4: the `heal` method must not appear in either output. Print `"Contains heal: X"` checking the compact text for the word `heal`.

Expected output:

{"name":"Sam","team":[{"name":"Zap","level":4}]} Size: 48 { "name": "Sam", "team": [ { "name": "Zap", "level": 4 } ] } Contains heal: false
Starter code
const trainer = { name: "Sam", team: [{ name: "Zap", level: 4 }], heal() { return "healed"; } }; // Write your functions here // Use them here
Back to the course