JavaScript has JSON support built in — two methods, JSON.parse() and JSON.stringify(), cover almost everything. This guide shows how to use them for real work: reading an API response, pretty-printing output, transforming values on the way in or out with the reviver and replacer, and avoiding the handful of errors that trip people up.
If you want the fundamentals of the format first, read what JSON is; this guide assumes you know objects from arrays.
JSON.parse: string to value
JSON.parse() takes a JSON string and returns the matching JavaScript value — an object, array, number, string, boolean or null:
const text = '{"name":"Ada","roles":["admin"],"active":true}';
const data = JSON.parse(text);
data.name; // "Ada"
data.roles[0]; // "admin"
typeof data; // "object"
With the Fetch API you rarely call parse yourself — response.json() does it for you:
const res = await fetch("/api/users/1");
if (!res.ok) throw new Error(res.status);
const user = await res.json(); // already parsed
JSON.stringify: value to string
The reverse direction serialises a value into a JSON string. The optional second and third arguments are the useful part — the third controls indentation:
const obj = { name: "Ada", scores: [1, 2, 3] };
JSON.stringify(obj); // '{"name":"Ada","scores":[1,2,3]}' (minified)
JSON.stringify(obj, null, 2); // pretty-printed with 2-space indent
Minified output is what you send over the network; indented output is for humans, logs and diffs. For a quick visual format without touching code, paste into the JSON formatter, or shrink a payload with JSON minify.
What does and does not survive a round trip
JSON.stringify() only knows the six JSON types, so some JavaScript values change or disappear:
undefined, functions and symbols are dropped from objects, and becomenullinside arrays.- Dates are serialised to ISO strings (via
Date.prototype.toJSON) and come back as strings — you must re-create theDateyourself. NaNandInfinitybecomenull.Map,Setand class instances lose their type and serialise as plain objects (or{}).
In other words, JSON.parse(JSON.stringify(x)) is a deep clone only for plain, JSON-safe data.
The replacer and the reviver
Both methods take a function that lets you transform values as they pass through. A replacer runs on the way out — use it to drop secret fields or convert values:
JSON.stringify(user, (key, value) =>
key === "password" ? undefined : value, 2);
A reviver runs on the way in — use it to turn date strings back into Date objects:
JSON.parse(text, (key, value) =>
key === "createdAt" ? new Date(value) : value);
The replacer can also be an array of keys to keep, which is a quick way to whitelist fields.
The errors that bite
- “Unexpected token < in JSON” — you parsed HTML, not JSON, because an API returned an error page. Log the raw text first; see debugging invalid JSON.
- Double parsing — calling
JSON.parse()on the result ofresponse.json()(already an object) throws. Parse once. - Circular references —
JSON.stringify()throws on an object that references itself; use a replacer that tracks seen objects. - Manual escaping — do not build JSON strings by hand; let
stringifyescape quotes and backslashes. If you must embed a JSON string inside another, the JSON escape tool does the nested escaping.
When a string simply will not parse, confirm it with the validator, which points at the exact position of the problem.
Sending JSON to a server
Posting data is the mirror image of reading it: stringify the body and set the content type so the server parses it correctly. With Fetch that looks like this:
await fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Ada", active: true })
});
Two things people forget: the body must be a string (pass the object straight through and it serialises to [object Object]), and the Content-Type header must say application/json or the server may not parse it. On the way back, read the response with await res.json() as shown earlier. Keeping stringify on the way out and json() on the way in is the whole round trip.
Deep clone, and why stringify is not the best way
A popular trick is JSON.parse(JSON.stringify(obj)) to deep-clone an object. It works only for JSON-safe data — it silently drops functions and undefined, turns dates into strings, and throws on circular references. Modern browsers and Node provide structuredClone(obj), which handles dates, Maps, Sets and cycles correctly. Use the stringify trick only as a quick clone for plain data you already know is JSON-safe.
Storing JSON in the browser
localStorage and sessionStorage hold strings only, so JSON is the natural way to persist structured state. Stringify on the way in and parse on the way out, and wrap the parse in a try/catch because stored data can be corrupted or absent:
localStorage.setItem("prefs", JSON.stringify(prefs));
let prefs = {};
try { prefs = JSON.parse(localStorage.getItem("prefs")) || {}; }
catch { prefs = {}; } // corrupted or missing - fall back
Never store secrets this way — it is readable by any script on the page, and it persists across sessions. Also note that storage has a size limit (around 5 MB per origin in most browsers), so very large objects belong in IndexedDB or on the server rather than in localStorage.
Formatting JSON for display
To show JSON to a user — in a debug panel or a textarea — pretty-print it with JSON.stringify(value, null, 2) and render it inside a <pre> element so whitespace is preserved. If you are pasting it somewhere for review instead, the formatter adds indentation and the validator confirms it is well-formed first. Keeping the minified version for transport and the indented version for display is the usual pattern. Remember to escape the text when injecting it into HTML, or render it with textContent rather than innerHTML, so a value containing tags cannot run as markup.
Key takeaways
JSON.parse()reads a string into a value;JSON.stringify()writes a value to a string.JSON.stringify(obj, null, 2)pretty-prints; no third argument minifies.- Only the six JSON types survive —
undefined, functions, dates and Maps are dropped or changed. - Use the replacer to omit fields and the reviver to rebuild dates.
- “Unexpected token” almost always means HTML arrived instead of JSON.