JSON.parse() and JSON.stringify() in JavaScript
JavaScript has two built-in functions for JSON: JSON.parse() turns JSON text into JavaScript values, and JSON.stringify() turns values back into JSON text. They look simple, but both have options and edge cases that cause real bugs. Here's what you need to know.
JSON.parse(): text to values
JSON.parse() takes a string of JSON and returns the JavaScript value it describes. JSON objects become plain objects, arrays become arrays, and strings, numbers, booleans and null become their JavaScript equivalents.
const text = '{"name": "Ada", "skills": ["math", "poetry"], "active": true}';
const user = JSON.parse(text);
user.name; // "Ada"
user.skills[1]; // "poetry"
typeof user; // "object"
JSON.parse("42"); // 42 (any JSON value works, not only objects)
JSON.parse('"hi"'); // "hi"If the text isn't valid JSON, JSON.parse throws a SyntaxError. When the JSON comes from somewhere you don't control, such as user input, a file or an API, wrap the call in try...catch:
function safeParse(text, fallback = null) {
try {
return JSON.parse(text);
} catch (error) {
console.error("Invalid JSON:", error.message);
return fallback;
}
}A few details of how values come out of JSON.parse:
- Big integers lose precision. JavaScript numbers are 64-bit floats, so integers above 9,007,199,254,740,991 (
Number.MAX_SAFE_INTEGER) can't be stored exactly.JSON.parse('{"id": 12345678901234567890}')gives12345678901234567000. That's why many APIs, such as Twitter's, send large IDs as strings. - Duplicate keys keep the last value.
{"a": 1, "a": 2}parses to{ a: 2 }without any warning. - Key order can change. Keys that look like whole numbers, such as
"1"or"2", are moved before all other keys in ascending order. Don't rely on key order to carry meaning; use an array if order matters.
JSON.stringify(): values to text
JSON.stringify() goes the other way. It's what you use to send data to an API, save it to a file or to localStorage, or log an object in full.
const order = { id: 5001, items: ["mug", "tea"], paid: true };
JSON.stringify(order);
// '{"id":5001,"items":["mug","tea"],"paid":true}'The result is always valid JSON: keys are double-quoted, strings are escaped, and there are no trailing commas. Generating JSON this way, instead of building strings by hand, avoids every mistake in common JSON errors.
Pretty printing with the space argument
By default the output is all on one line. The third argument adds line breaks and indentation: pass a number of spaces (up to 10) or a string such as "\t".
JSON.stringify({ a: [1, 2] }, null, 2);
// {
// "a": [
// 1,
// 2
// ]
// }console.log(JSON.stringify(value, null, 2)) is a handy way to see an entire nested object, because browser consoles collapse deep objects. The formatting guide covers other ways to format JSON.
What JSON.stringify changes or drops
JSON has fewer types than JavaScript, so some values can't survive the trip. This example shows what happens to each:
JSON.stringify({
date: new Date(0),
missing: undefined,
greet() {},
notANumber: NaN,
forever: Infinity,
map: new Map([[1, 2]]),
set: new Set([1]),
list: [undefined, () => 1, NaN],
});
// '{"date":"1970-01-01T00:00:00.000Z","notANumber":null,"forever":null,
// "map":{},"set":{},"list":[null,null,null]}'- Dates become ISO 8601 strings. When you parse the JSON again you get a string, not a
Date. See revivers below. undefined, functions and symbols are left out of objects completely, and turned intonullinside arrays.NaNandInfinitybecomenull.- Maps and Sets become empty objects, silently losing their contents. Convert them first, for example with
Object.fromEntries(map)or[...set].
JSON isn't a deep copy tool
JSON.parse(JSON.stringify(obj)) was once a popular way to copy an object, but it loses dates, Maps, Sets and undefined values as shown above. Modern browsers and Node have structuredClone(obj), which copies all of these correctly.
Choosing what to include: replacers and toJSON
The second argument, the replacer, controls what gets included. Pass an array of key names to keep only those keys, which is a simple way to avoid leaking a field like a password into logs:
const user = { id: 1, name: "Ada", password: "hunter2" };
JSON.stringify(user, ["id", "name"]); // '{"id":1,"name":"Ada"}'Or pass a function, which is called for every key and value. Whatever it returns is used instead; returning undefined leaves the key out:
JSON.stringify(data, (key, value) => {
if (key === "password") return undefined; // drop it
if (typeof value === "bigint") return value.toString(); // BigInt -> string
return value;
});Objects can also decide how they're serialized by defining a toJSON() method.Date has one built in, which is why dates turn into strings.
Restoring dates with a reviver
JSON.parse accepts a second argument too: a reviver function that can transform each value as it's read. The most common use is turning date strings back into Date objects:
const text = '{"id": 7, "createdAt": "2026-12-05T10:00:00.000Z"}';
const record = JSON.parse(text, (key, value) =>
key === "createdAt" ? new Date(value) : value
);
record.createdAt instanceof Date; // trueErrors you'll run into
TypeError: Converting circular structure to JSON: the object refers to itself somewhere, directly or through a chain of other objects. DOM elements, Expressreqobjects and many class instances have circular references. Stringify only the fields you need, or use a replacer to skip the circular ones.TypeError: Do not know how to serialize a BigInt: JSON has no BigInt type. Convert BigInts to strings with a replacer, as shown above.SyntaxErrorfromJSON.parse: the text isn't valid JSON. What JSON error messages mean explains each message.
JSON with fetch and localStorage
You'll rarely call JSON.parse on API responses yourself, because response.json() does it for you. Sending JSON is the other half: stringify the body and set the content type so the server knows how to read it.
// Reading
const res = await fetch("/api/orders/5001");
const order = await res.json(); // already parsed; don't JSON.parse it again
// Sending
await fetch("/api/orders", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ items: ["mug"], qty: 2 }),
});localStorage can only store strings, so objects need to be stringified on the way in and parsed on the way out. Remember that getItem returns null for a key that doesn't exist:
localStorage.setItem("settings", JSON.stringify({ theme: "dark" }));
const settings = JSON.parse(localStorage.getItem("settings")) ?? { theme: "light" };