Errors
JSON.parse() and JSON.stringify()
Turning data into text and back — for the network, files and localStorage.
Why it exists
Between programs, over the network, in files and in localStorage, only text can be passed. But objects and arrays are what's convenient to work with. JSON is a text format shared by every language, resembling JavaScript's object notation. stringify packs data into such text before sending; parse unpacks received text back into objects.
Where it's used
- API requests:
fetch(url, { body: JSON.stringify(data) })andawait response.json(). - Storage in the browser:
localStorage.setItem("cart", JSON.stringify(cart)). - Config files: package.json,
tsconfig.json. - Deep-copying simple data:
JSON.parse(JSON.stringify(obj))(with caveats).
Syntax
JSON.stringify(value)
JSON.parse(string)Examples
JSON.parse('{"name":"Byte","age":3}').age; // → 3const cart = [{ id: 1, qty: 2 }];
const text = JSON.stringify(cart);
text; // → '[{"id":1,"qty":2}]'
JSON.parse(text)[0].qty; // → 2JSON.stringify({ a: 1, b: undefined, c: NaN }); // → '{"a":1,"c":null}'undefined disappears, NaN becomes nulllet settings;
try {
settings = JSON.parse("{theme: dark}");
} catch {
settings = { theme: "light" };
}
settings.theme; // → "light"try...catchResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
JSON resembles JavaScript literals but is stricter: keys only in double quotes, strings in double quotes too, no comments, no comma after the last item, no undefined, functions, NaN or Infinity.
JSON.stringify(value) walks the value and builds text. Properties whose value is undefined, and functions, are skipped; NaN and Infinity become null; dates become strings. A third argument adds indentation: JSON.stringify(obj, null, 2).
JSON.parse(text) reads the text and creates new objects, arrays, strings and numbers. If the text breaks the format's rules, it throws a SyntaxError rather than returning an "empty" value. So data from an unreliable source is parsed inside try...catch.
Valid JSON isn't only objects: "42", "null", "true" and '"text"' parse too.
Traps
How it differs from…
try...catchtry...catch is the essential companion of
JSON.parsefor any data that might be corrupted.- Objects
{ } A JavaScript object literal is more flexible than JSON: keys needn't be quoted, and values can be functions and undefined.
When to pick something else
Practice
Lessons where this appears
- A safe JSON.parseLab · Chapter 15 · Errors
- A call to the warehouseTale · Chapter 21 · The network: fetch and HTTP
- A customer's ordersLab · Chapter 21 · The network: fetch and HTTP
- Memory after a napTale · Chapter 22 · localStorage and JSON
- The case of the cart that crashed after a reloadInvestigation · Chapter 22 · localStorage and JSON
- Recent searchesLab · Chapter 22 · localStorage and JSON