Lesson 14 of 28

In progress

Course progress

JavaScript

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

JavaScript
Editable. Runs in your browser.





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

JavaScript
Editable. Runs in your browser.





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.

JavaScript
Editable. Runs in your browser.





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:

JavaScript
Editable. Runs in your browser.





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.

JavaScript
Editable. Runs in your browser.





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.

JavaScript
Editable. Runs in your browser.





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
JavaScript
Editable. Runs in your browser.





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

  • stringify and parse convert 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?
Not directly. Convert with `toISOString()` and parse back with `new Date(value)`. Storing the ISO string is more portable than a timestamp in milliseconds.
Is JSON faster than other formats?
It is fast enough and universally supported. Protocol Buffers and similar formats are smaller and faster, at the cost of tooling and readability.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.