stringify) & Parsing (parse)JSON (JavaScript Object Notation) is a lightweight, text-based data-interchange format. JavaScript provides the JSON namespace object to serialize objects into JSON strings (JSON.stringify()) and parse JSON strings into objects (JSON.parse()).
flowchart LR
JSObj["JavaScript Object / Value"] -->|JSON.stringify(obj, replacer)| JSONStr["JSON String Text ('{"id": 10}')"]
JSONStr -->|JSON.parse(str, reviver)| RestoredObj["New Reconstructed JS Object"]
| JavaScript Type | Supported in JSON? | Behavior in JSON.stringify() |
|---|---|---|
| String, Number, Boolean, Null | Yes | Serialized directly to JSON equivalent. |
| Object, Array | Yes | Serialized to {} and []. |
| Function, Symbol, Undefined | No | Omitted / Stripped from object properties. |
Date Instance |
Partial | Converted to ISO date string. |
BigInt |
No | Throws TypeError unless handled in replacer. |
// Demonstrating JSON parse, stringify, replacer, and reviver
const userAccount = {
id: 101,
username: "maksudur",
createdAt: new Date(),
secretToken: "SECRET_999", // Sensitive property to filter
performAction: () => console.log("Action") // Function will be stripped
};
// 1. Custom Replacer: Exclude sensitive properties and format JSON
const jsonString = JSON.stringify(userAccount, (key, value) => {
if (key === "secretToken") return undefined; // Exclude secretToken
return value;
}, 2); // 2-space indentation
console.log("Serialized JSON Output:
" + jsonString);
// 2. Custom Reviver: Convert ISO date strings back into Date instances during parse
const parsedUser = JSON.parse(jsonString, (key, value) => {
if (typeof value === "string" && /^\d{4}-\d{2}-\d{2}T/.test(value)) {
return new Date(value); // Revive string into Date object
}
return value;
});
console.log("Parsed User Object:", parsedUser);
console.log(`Is createdAt a valid Date instance? ${parsedUser.createdAt instanceof Date}`);
TypeError: Converting circular structure to JSON."key": "value"). Single quotes are invalid JSON syntax.JSON.parse() in try...catch: Malformed JSON strings throw unhandled SyntaxError exceptions during parsing.Why does JSON.stringify({ fn: () => {}, val: undefined }) evaluate to "{}"?
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.