JavaScript JSON: JSON.stringify and JSON.parse
JSON (JavaScript Object Notation) is a text format for data. It borrows JavaScript's syntax for objects and arrays, but it is just text, so any language can read and write it. Web APIs, configuration files and browser storage all use JSON. JavaScript converts with two functions: JSON.stringify() turns a value into JSON text, and JSON.parse() turns JSON text back into a value.
What JSON allows
JSON is stricter than JavaScript:
- Keys must be strings in double quotes.
- Strings use double quotes only.
- Values can be strings, numbers,
true,false,null, arrays and objects. There is noundefined, no functions, no dates, no comments, and no trailing commas.
JSON.stringify
JSON.stringify(order) produces a compact single line. Properties whose value is undefined or a function are left out entirely, which is why note disappears and "note" in back is false after the round trip. A Date becomes an ISO 8601 string, such as "2026-11-21T00:00:00.000Z", because dates define a toJSON() method. When parsed back, it stays a string; convert it with new Date(text) if you need a date again.
The third argument controls indentation for human-readable output: JSON.stringify(value, null, 2) indents nested levels by two spaces. The second argument, here null, can filter or transform properties.
Expected output
{"id":7,"customer":"Liam","items":["River of Salt","Paper Cranes"],"paid":true}
string
Paper Cranes true false
{
"a": 1,
"b": [
1,
2
]
}
{"when":"2026-11-21T00:00:00.000Z"}
SyntaxErrorJSON.parse
JSON.parse(text) returns ordinary arrays and objects that you use like any other value. If the text is not valid JSON, for example because it uses single quotes or unquoted keys like {name: 'Ava'}, it throws a SyntaxError. Data from outside your program can be malformed, so wrap JSON.parse in try...catch when the input is not under your control.
JSON in practice
With fetch(), call await response.json(), which reads the body and parses it in one step. To save data in the browser, store JSON.stringify(value) in localStorage and parse it when reading it back.
A common trick for copying plain data is JSON.parse(JSON.stringify(obj)). It works, but drops undefined, turns dates into strings and fails on circular references. structuredClone() is the better tool.
Common mistakes
- Writing JSON by hand with single quotes or trailing commas.
- Expecting dates to come back as
Dateobjects. - Parsing data twice, or calling
JSON.parseon something that is already an object.
Summary
JSON.stringifyconverts values to JSON text;JSON.parseconverts back.- JSON needs double-quoted keys and strings and has no
undefined, functions or comments. - Pretty-print with
JSON.stringify(value, null, 2). - Invalid JSON makes
JSON.parsethrow aSyntaxError.
Quiz: JSON