Chapters: JavaScript HTML & CSS JSON XML YAML ← Full TOC

← JSON Index

⚡ JSON in JavaScript — JSON.parse, JSON.stringify, fetch, and manipulation

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.

📋 Reference

ItemSyntax / ValueDescription
JSON.parseJSON.parse(text, reviver?) → anyParse JSON string to JavaScript value
JSON.stringifyJSON.stringify(value, replacer?, space?) → stringSerialize JavaScript value to JSON string
space parameterJSON.stringify(obj, null, 2)Indent with 2 spaces for pretty-print
replacer functionJSON.stringify(obj, (key,val) => ...)Transform values during serialization
reviver functionJSON.parse(str, (key,val) => ...)Transform values during parsing
structuredClonestructuredClone(obj)Deep clone JSON-serializable object (no JSON roundtrip needed)
JSON.parse errortry { JSON.parse(str) } catch(e) {}Always wrap in try/catch — throws SyntaxError on invalid JSON
undefined handlingJSON.stringify({a:undefined}) → '{}'undefined properties are omitted
Date handlingnew Date().toISOString()Dates serialize as ISO 8601 strings — revive manually
toJSON methodobj.toJSON = () => ({...})Custom serialization for any object
BigInt errorJSON.stringify(42n) → TypeErrorBigInt not supported — convert to string first
Circular referenceJSON.stringify({a:obj,obj:{a:obj}}) → TypeErrorCircular refs not supported — use structuredClone or replacer
fetch + JSONfetch(url).then(r=>r.json())Fetch and parse JSON response
POST JSONfetch(url,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)})Send JSON in POST request
JSON SchemaJSON Schema is a vocabulary for validating JSONNot built-in — use ajv library
JSON Pointer'/path/to/field' — RFC 6901Navigate JSON by path string
JSON PatchArray of operations — RFC 6902Atomic JSON document updates
JSON Merge PatchPartial JSON for updates — RFC 7396Simpler partial update format

💡 Example

// 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)

← JSON Syntax  |  🏠 Index  |  JSON in Python →