Guide
JSON.parse and JSON.stringify explained
The two built-in JavaScript functions for working with JSON look simple, but they have options and surprises worth knowing. Here is a practical tour with examples.
The two functions
JavaScript has a built-in JSON object with two methods that do almost all
JSON work:
JSON.parse(text)turns a JSON string into JavaScript values: objects, arrays, strings, numbers, booleans andnull.JSON.stringify(value)turns JavaScript values into a JSON string.
const text = '{"name": "Ada", "languages": ["en", "fr"]}'
const user = JSON.parse(text)
user.languages.push('it')
const back = JSON.stringify(user)
// '{"name":"Ada","languages":["en","fr","it"]}'
Both run synchronously and are available everywhere: browsers, Node.js, Deno, Bun and web
workers. When you call response.json() after fetch, the browser
does the same parsing for you.
JSON.parse and invalid input
If the text isn’t valid JSON, JSON.parse throws a SyntaxError.
Text from a network request, a file or a user should always be parsed inside
try/catch:
function safeParse(text, fallback = null) {
try {
return JSON.parse(text)
} catch (err) {
console.warn('Invalid JSON:', err.message)
return fallback
}
}
const settings = safeParse(localStorage.getItem('settings'), {})
The error message says where parsing stopped. The guide How to fix JSON errors explains each message.
Two parsing details worth knowing:
- Duplicate keys:
JSON.parse('{"a":1,"a":2}').ais2. The last value wins, without any warning. - Large numbers lose precision:
JSON.parse('9007199254740993')returns9007199254740992. See Handling big numbers in JSON.
Transforming values with a reviver
JSON.parse takes an optional second argument, a reviver
function. It is called for every key and value, from the deepest values up, and whatever
it returns replaces the value. Returning undefined removes the key.
The classic use is turning date strings back into Date objects, since JSON has no date type:
const json = '{"title": "Launch", "at": "2026-03-14T09:26:53Z"}'
const event = JSON.parse(json, (key, value) => {
if (key === 'at') return new Date(value)
return value
})
event.at instanceof Date // true
Always return value for keys you don’t handle, otherwise they disappear from
the result.
Formatting with JSON.stringify
JSON.stringify(value, replacer, space) takes two optional arguments. The
third, space, controls indentation:
JSON.stringify({ a: [1, 2] }) // '{"a":[1,2]}'
JSON.stringify({ a: [1, 2] }, null, 2) // 2-space indentation
JSON.stringify({ a: [1, 2] }, null, '\t') // tabs
A number means that many spaces (at most 10). A string is used as the indent itself (at most its first 10 characters). Without it, the output is minified onto one line, which is what you want for sending over the network.
Choosing keys with a replacer
The second argument, replacer, can be an array of keys to keep:
const user = { id: 1, name: 'Ada', password: 'secret' }
JSON.stringify(user, ['id', 'name'])
// '{"id":1,"name":"Ada"}'
Or a function, called for each key and value, like a reviver in reverse:
JSON.stringify(user, (key, value) =>
key === 'password' ? undefined : value
)
// '{"id":1,"name":"Ada"}'
Returning undefined from a replacer leaves the key out. Note that the
function is first called with an empty key "" for the whole object, so
return value by default.
What JSON.stringify changes or drops
JSON supports fewer types than JavaScript, so JSON.stringify has to convert
or skip some values. These are easy to miss because they don’t throw errors:
| Value | In an object | In an array |
|---|---|---|
undefined, functions, symbols | Key is left out | Becomes null |
NaN, Infinity, -Infinity | null | null |
Date | ISO string, e.g. "1970-01-01T00:00:00.000Z" | Same |
Map, Set, RegExp | {} (contents lost) | {} |
BigInt | Throws TypeError: Do not know how to serialize a BigInt | |
| Object that refers to itself | Throws TypeError: Converting circular structure to JSON | |
To keep a Map, convert it first: Object.fromEntries(map) for
string keys, or [...map] for an array of pairs. Use
[...set] for a Set.
Also, JSON.stringify(undefined) returns undefined, not a string.
Sending that as a request body is a common source of “Unexpected end of JSON input” on
the server.
Custom output with toJSON
If an object has a toJSON() method, JSON.stringify serializes
whatever it returns instead. That is how Date becomes an ISO string. You can
use it in your own classes:
class Money {
constructor(cents, currency) {
this.cents = cents
this.currency = currency
}
toJSON() {
return { amount: (this.cents / 100).toFixed(2), currency: this.currency }
}
}
JSON.stringify({ total: new Money(1999, 'EUR') })
// '{"total":{"amount":"19.99","currency":"EUR"}}'
Key order
Keys come out in the object’s property order: integer-like keys first in ascending order,
then other keys in the order they were added. So
JSON.stringify({ b: 1, 2: 'x', a: 2, 1: 'y' }) gives
{"1":"y","2":"x","b":1,"a":2}. Don’t compare JSON strings to check whether two
objects are equal; a structural comparison like the JSON Diff
tool ignores order.
Deep copying with JSON (and why not to)
JSON.parse(JSON.stringify(obj)) is a well-known trick for a deep copy, but it
loses everything in the table above: dates become strings, Map and
Set become empty objects, and undefined values vanish. Modern
environments have structuredClone(obj), which copies dates, maps, sets,
typed arrays and circular references correctly. Use that instead.
Summary
JSON.parsereads JSON text; wrap it intry/catchand use a reviver to restore dates.JSON.stringifywrites JSON; usespaceto format, and a replacer ortoJSONto control output.- Watch for silently dropped values (
undefined, functions,Map),NaNturning intonull, and errors onBigIntand circular references. - Use
structuredClonefor deep copies.