JSON Serialization in JavaScript
Introduction
JSON (JavaScript Object Notation) is the standard text format for APIs, config files, and logs. JavaScript provides JSON.stringify and JSON.parse to convert between objects and strings. This chapter shows safe patterns, common pitfalls, and how JSON relates to object literals you already know.
Prerequisites
Why JSON Matters
- REST APIs send/receive JSON bodies
package.jsonand many config files are JSON- Browser
localStorageoften stores JSON strings
JSON supports objects, arrays, strings, numbers, booleans, and null—not functions, undefined, or Date objects (dates become strings if you convert manually).
JSON.stringify — Object to String
// Serialize object
const user = { id: 1, name: "Ada", active: true };
const text = JSON.stringify(user);
console.log(text);
console.log(typeof text);Pretty-print for debugging:
// Indented output
const payload = { ok: true, items: [{ id: 1 }, { id: 2 }] };
console.log(JSON.stringify(payload, null, 2));JSON.parse — String to Object
// Parse API-like response
const raw = '{"id":2,"name":"Lin","active":false}';
const data = JSON.parse(raw);
console.log(data.name);
console.log(data.active);Always wrap parse in try/catch for untrusted input:
// Safe parse
const input = "{ not valid json }";
try {
const obj = JSON.parse(input);
console.log(obj);
} catch (error) {
console.error("Invalid JSON:", error.message);
}Tip
Format JSON online
For large payloads during learning, you can paste JSON into https://tool.iristechme.com/en/json-formatter to inspect structure quickly.
Values That Disappear or Change
// undefined and functions are omitted or unsupported
const odd = {
a: 1,
b: undefined,
c: () => "hi",
};
console.log(JSON.stringify(odd));undefined in arrays becomes null in JSON output.
Dates and Custom Types
JSON has no date type—serialize explicitly:
// ISO date string
const event = {
name: "Deploy",
at: new Date().toISOString(),
};
const json = JSON.stringify(event);
console.log(json);Parse back and convert if needed:
// Parse and reconstruct Date
const parsed = JSON.parse(json);
const when = new Date(parsed.at);
console.log(when.toLocaleString());Reading JSON Files in Node.js (Preview)
Later with file handling, you will load JSON from disk. Pattern:
// Conceptual pattern (requires fs in real Node scripts)
// const text = await fs.readFile("config.json", "utf8");
// const config = JSON.parse(text);Mini Example: Save Cart to localStorage (Browser)
// Browser-only example — run in DevTools console
const cart = { items: [{ sku: "A1", qty: 2 }], updatedAt: Date.now() };
const saved = JSON.stringify(cart);
localStorage.setItem("cart", saved);
const restored = JSON.parse(localStorage.getItem("cart") ?? "{}");
console.log(restored);In Node, use files or a database instead of localStorage.
FAQ
Is JSON exactly JavaScript object syntax?
Very close, but stricter: keys must be double-quoted strings, no trailing commas, no comments, no functions.
Can JSON be large?
Yes—stream or paginate in production. For learning, pretty-print small samples.
What is reviver / replacer in parse/stringify?
Optional hooks to transform values during parse/stringify—advanced customization.
What comes next?
Arrays—lists of values and array methods.