Lesson 14 of 28
In progress
JSON: the shape data travels in
Turn objects into JSON text and back, handle malformed data, and recognise the shapes APIs actually return.
Every API response, every saved setting and every configuration file in this track is JSON. It is a text format with a small grammar, and JavaScript can read it in one call.
What you will learn
- Convert between values and JSON text.
- Handle malformed JSON without breaking the page.
- Recognise the common API response shapes.
Two methods
Editable. Runs in your browser.
const text = JSON.stringify(task);
console.log(text);
const back = JSON.parse(text);
console.log(back.title);
console.log(Array.isArray(back.tags));
Press Run to see the output.
JSON.stringify produces text; JSON.parse produces values. The round trip preserves objects, arrays, strings, numbers, booleans and null.
It does not preserve functions, undefined, Date objects or Map/Set. A Date becomes an ISO string, a function disappears, and undefined properties are dropped. That is why a round trip is a useful test of a data model: anything that changes shape was never JSON data.
Formatting and options
Editable. Runs in your browser.
console.log(JSON.stringify(data));
console.log(JSON.stringify(data, null, 2));
Press Run to see the output.
The third argument is indentation: a number of spaces or a string such as "t". Use it for files a person may read, and compact output for storage or network payloads.
JSON.stringify(value, replacer, space) also accepts a replacer that filters or transforms keys. The array form whitelists keys; the function form runs per key. It is useful for hiding fields, though building the object you want is usually clearer.
Malformed JSON
JSON.parse throws SyntaxError on invalid input. Since saved data can be truncated or hand-edited, parse defensively when the source is not under your control.
Editable. Runs in your browser.
console.log(readSettings('{"theme":"dark"}'));
console.log(readSettings("{oops}"));
Press Run to see the output.
Returning an empty object keeps the page running. The warning keeps the failure visible to you. Logging the raw text can leak data, so log the message rather than the content.
The shapes APIs return
Three shapes cover most endpoints:
Editable. Runs in your browser.
console.log(single.name);
console.log(collection.length);
console.log(envelope.data[0].id, envelope.meta.total);
Press Run to see the output.
An envelope with data and meta is common when pagination is involved. Read the documented shape instead of guessing, and check for a missing array before calling map on it: const items = payload.data ?? [].
Validating a shape before using it
Parsing only proves the text is JSON. It says nothing about whether the object has the fields you need. A response missing items, or with items as an object instead of an array, will fail later at an unrelated line.
Editable. Runs in your browser.
return items
.filter((item) => item && typeof item.title === "string")
.map((item) => ({ title: item.title, done: Boolean(item.done) }));
}
console.log(normalise({ items: [{ title: "Read" }, { nope: true }] }));
console.log(normalise(null));
Press Run to see the output.
This function turns unknown input into a predictable array of records. Every consumer after it can trust the shape, which is much easier than scattering checks through rendering code. Name it after what it returns, and keep the rules in one place.
The same idea applies to data read from storage, which a user can edit in DevTools. Treat it as untrusted input even though your own code wrote it. Returning fresh objects also stops rendering code from mutating the parsed payload by accident, which is a subtle bug that is hard to trace later.
JSON is not JavaScript
JSON requires double quotes around keys and strings, forbids trailing commas, and has no comments, functions or undefined. A JavaScript object literal is more permissive, which is why copying one into a .json file often fails.
Editable. Runs in your browser.
try {
JSON.parse("{a: 1}");
} catch (error) {
console.log(error.name);
}
Press Run to see the output.
The unquoted key throws a SyntaxError. That single rule accounts for most hand-written JSON failures.
JSON.stringify drops undefined properties silently, so an object can come back from storage missing a field you expected. Give every field a real default before saving, or normalise after parsing, rather than assuming the round trip is lossless.
Given an array of products, produce a JSON string containing only name and price, formatted with two spaces. Then parse it back and log the total price.
Show solution
Editable. Runs in your browser.
const text = JSON.stringify(
products.map(({ name, price }) => ({ name, price })),
null,
2
);
console.log(text);
const back = JSON.parse(text);
console.log(back.reduce((sum, item) => sum + item.price, 0));
Press Run to see the output.
Mapping to a new object removes the stock field deliberately, instead of relying on a replacer. The parsed array is plain data again, so reduce works without surprises.
Recap
stringifyandparseconvert between values and text; functions and undefined do not survive.- Parse defensively when data may be corrupted, and never log raw user content.
- JSON needs double quotes and has no comments or trailing commas.
Next, you will request JSON from a server with fetch and handle the response properly.
Can I store a Date in JSON?
Is JSON faster than other formats?
Progress is saved in this browser only. No account, no email.