JavaScript has built-in JSON support. JSON.parse() converts JSON string to JavaScript object. JSON.stringify() converts JavaScript value to JSON string. Both support replacer/reviver for custom transformations.
| Item | Syntax / Value | Description |
|---|---|---|
| JSON.parse | JSON.parse(text, reviver?) → any | Parse JSON string to JavaScript value |
| JSON.stringify | JSON.stringify(value, replacer?, space?) → string | Serialize JavaScript value to JSON string |
| space parameter | JSON.stringify(obj, null, 2) | Indent with 2 spaces for pretty-print |
| replacer function | JSON.stringify(obj, (key,val) => ...) | Transform values during serialization |
| reviver function | JSON.parse(str, (key,val) => ...) | Transform values during parsing |
| structuredClone | structuredClone(obj) | Deep clone JSON-serializable object (no JSON roundtrip needed) |
| JSON.parse error | try { JSON.parse(str) } catch(e) {} | Always wrap in try/catch — throws SyntaxError on invalid JSON |
| undefined handling | JSON.stringify({a:undefined}) → '{}' | undefined properties are omitted |
| Date handling | new Date().toISOString() | Dates serialize as ISO 8601 strings — revive manually |
| toJSON method | obj.toJSON = () => ({...}) | Custom serialization for any object |
| BigInt error | JSON.stringify(42n) → TypeError | BigInt not supported — convert to string first |
| Circular reference | JSON.stringify({a:obj,obj:{a:obj}}) → TypeError | Circular refs not supported — use structuredClone or replacer |
| fetch + JSON | fetch(url).then(r=>r.json()) | Fetch and parse JSON response |
| POST JSON | fetch(url,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)}) | Send JSON in POST request |
| JSON Schema | JSON Schema is a vocabulary for validating JSON | Not built-in — use ajv library |
| JSON Pointer | '/path/to/field' — RFC 6901 | Navigate JSON by path string |
| JSON Patch | Array of operations — RFC 6902 | Atomic JSON document updates |
| JSON Merge Patch | Partial JSON for updates — RFC 7396 | Simpler partial update format |
// JSON in JavaScript — complete reference
// ── 1. Parse & Stringify ─────────────────────────────────────
const json = '{"name":"Alice","score":95,"joined":"2024-01-15T00:00:00.000Z"}';
const obj = JSON.parse(json, (key, val) =>
key === 'joined' ? new Date(val) : val); // reviver: restore Date
console.log(obj.name, obj.score, obj.joined instanceof Date);
const pretty = JSON.stringify(obj, null, 2); // pretty-print
console.log(pretty);
const compact = JSON.stringify(obj, ['name','score']); // pick fields
console.log(compact); // {"name":"Alice","score":95}
// ── 2. replacer function ─────────────────────────────────────
const data = { name: 'Alice', password: 'secret', score: 95, created: new Date() };
const safe = JSON.stringify(data, (key, val) => {
if (key === 'password') return undefined; // omit sensitive field
if (val instanceof Date) return val.toISOString();
return val;
}, 2);
console.log(safe); // no password field
// ── 3. Deep clone ────────────────────────────────────────────
const original = { scores: [1,2,3], nested: { val: 42 } };
const clone1 = JSON.parse(JSON.stringify(original)); // old way
const clone2 = structuredClone(original); // modern way
clone2.scores.push(4);
console.log(original.scores); // [1,2,3] — unchanged
// ── 4. Safe parse ────────────────────────────────────────────
const safeParseJSON = (str, fallback = null) => {
try { return JSON.parse(str); }
catch { return fallback; }
};
console.log(safeParseJSON('{"a":1}')); // {a:1}
console.log(safeParseJSON('not json')); // null
// ── 5. Fetch JSON API ────────────────────────────────────────
async function fetchPost(id) {
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json(); // automatic JSON.parse
}
// ── 6. POST JSON ─────────────────────────────────────────────
async function createPost(data) {
const res = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
return res.json();
}
(async () => {
const post = await fetchPost(1);
console.log('Post:', post.title.substring(0, 40));
const created = await createPost({ title: 'MyWebUniversity', body: 'test', userId: 1 });
console.log('Created id:', created.id);
})().catch(e => console.log('Error:', e.message));
// node json_demo.js (Node 18+ has built-in fetch)