JSON (JavaScript Object Notation) is a lightweight, language-independent text format for storing and exchanging structured data across APIs. JavaScript gives you two built-in helpers: JSON.stringify() to turn objects into JSON text and JSON.parse() to turn JSON text back into JavaScript values.
JSON looks like a JavaScript object literal, yet JSON syntax is much stricter:
"double quotes", never 'single quotes'.{ "a": 1, } or // comments will fail JSON.parse().JSON.stringify() strips undefined properties and functions, turns NaN and Infinity into null, and throws on BigInt or circular references.Pass null, 2 to JSON.stringify() for readable two-space indentation when logging or saving config files, and always wrap JSON.parse() in try...catch.
const payload = {
id: 42,
tags: ["js", "json"],
createdAt: new Date("2026-11-12T10:00:00Z"),
helper: () => "ignored", // Stripped by JSON.stringify
};
const jsonText = JSON.stringify(payload, null, 2);
console.log("Serialized JSON:
" + jsonText);
function parseSafely(raw) {
try {
return JSON.parse(raw);
} catch (err) {
console.error("Invalid JSON:", err.message);
return null;
}
}
console.log("Parsed object:", parseSafely(jsonText));
JSON.parse() without try...catch: Malformed localStorage strings or broken API text will throw a SyntaxError and crash your UI.Date strings to revive automatically: JSON.parse() returns ISO date strings as plain strings, not Date instances; convert them back with new Date(obj.createdAt).JSON.parse(JSON.stringify(obj)) for cloning everything: It silently drops undefined, functions, Map, Set, and breaks on BigInt. Prefer structuredClone(obj) for deep cloning.JSON.parse()?The optional second parameter (key, value) => ... transforms parsed values as they load—ideal for turning ISO timestamp strings back into Date objects.
JSON.stringify() filter which keys get serialized?Yes, pass an array of allowed property names as the second argument, such as JSON.stringify(user, ["id", "name"]), to exclude sensitive fields like passwordHash.
JSON.stringify({ x: undefined }) return "{}"?JSON has no undefined type, so JSON.stringify() omits object properties whose value is undefined (and converts undefined inside arrays to null).
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.