JavaScript JSON
Parse & Stringify
Convert between JSON strings and objects
// Parse JSON string to object
const data = JSON.parse('{"name":"sw01","port":22}');
console.log(data.name); // "sw01"
// Stringify object to JSON string
const json = JSON.stringify({ name: "sw01", port: 22 });
// '{"name":"sw01","port":22}'
// Pretty print
const pretty = JSON.stringify(data, null, 2);
// {
// "name": "sw01",
// "port": 22
// }
Replacer & Reviver
Transform during serialization/deserialization
// Replacer — filter or transform during stringify
const user = { name: "Evan", password: "secret", role: "admin" };
const safe = JSON.stringify(user, (key, value) => {
if (key === "password") return undefined; // omit
return value;
});
// '{"name":"Evan","role":"admin"}'
// Replacer as array — whitelist fields
const minimal = JSON.stringify(user, ["name", "role"]);
// Reviver — transform during parse
const data = JSON.parse('{"date":"2026-04-10T00:00:00Z"}', (key, value) => {
if (key === "date") return new Date(value);
return value;
});
console.log(data.date instanceof Date); // true
Deep Clone
structuredClone vs JSON round-trip
// Modern — structuredClone (handles Date, Map, Set, ArrayBuffer)
const clone = structuredClone(original);
// Legacy — JSON round-trip (loses functions, undefined, Date objects)
const clone = JSON.parse(JSON.stringify(original));
// Gotcha: JSON round-trip silently drops:
// - undefined values
// - functions
// - Symbol keys
// - circular references (throws TypeError)
structuredClone() is the correct way to deep clone in modern JavaScript. JSON round-trip is a hack that loses type information.
Handling Errors
Safe parsing
function safeParse(text, fallback = null) {
try {
return JSON.parse(text);
} catch (err) {
console.error("Invalid JSON:", err.message);
return fallback;
}
}
const config = safeParse(rawInput, { port: 8080 });
JSON.parse throws SyntaxError on invalid input. Always wrap it in try/catch when parsing user input or external data.
Working with APIs
Common JSON patterns
// POST JSON to API
const response = await fetch("/api/hosts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "sw01", ip: "10.50.1.10" }),
});
const result = await response.json();
// Read JSON file (Node.js)
import { readFile } from "fs/promises";
const config = JSON.parse(await readFile("config.json", "utf-8"));
// Write JSON file (Node.js)
import { writeFile } from "fs/promises";
await writeFile("output.json", JSON.stringify(data, null, 2));