100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

JavaScript JSON Handling Cheat Sheet

JavaScript JSON Handling Cheat Sheet

Covers converting between JavaScript values and JSON strings with JSON.stringify and JSON.parse, plus custom serialization and common gotchas.

1 PageBeginnerMar 22, 2026

JSON.stringify

Serialize JavaScript values into a JSON string.

javascript
const user = { name: "Alice", age: 30, active: true };JSON.stringify(user);// '{"name":"Alice","age":30,"active":true}'JSON.stringify(user, null, 2);// Pretty-printed with 2-space indentationJSON.stringify(user, ["name", "age"]);// '{"name":"Alice","age":30}' -- replacer array whitelists keysJSON.stringify(user, (key, value) =>  typeof value === "number" ? value * 2 : value);// Replacer function transforms values before serialization

JSON.parse

Deserialize a JSON string back into JavaScript values.

javascript
const raw = '{"name":"Alice","age":30}';const user = JSON.parse(raw);user.name;   // "Alice"// Reviver function to transform values while parsingconst withDate = JSON.parse(  '{"createdAt":"2024-01-01T00:00:00Z"}',  (key, value) =>    key === "createdAt" ? new Date(value) : value);withDate.createdAt instanceof Date;   // true// Invalid JSON throws a SyntaxError -- always wrap in try/catch for untrusted inputtry {  JSON.parse("{invalid}");} catch (e) {  console.error("Bad JSON:", e.message);}

Common Gotchas

Values that don't round-trip the way you'd expect.

javascript
JSON.stringify(undefined);              // undefined (not a string!)JSON.stringify({ a: undefined });       // '{}' -- undefined values are droppedJSON.stringify([undefined, 1]);         // '[null,1]' -- undefined becomes null in arraysJSON.stringify({ fn() {} });            // '{}' -- functions are omittedJSON.stringify(NaN);                    // 'null'JSON.stringify(Infinity);                // 'null'const circular = {};circular.self = circular;JSON.stringify(circular);   // Throws: TypeError - Converting circular structure to JSONJSON.stringify({ d: new Date() });// Dates serialize via their toJSON() method -> ISO 8601 string

Custom Serialization with toJSON

Control how an object serializes by defining toJSON().

javascript
class Money {  constructor(cents) {    this.cents = cents;  }  toJSON() {    // JSON.stringify calls toJSON() automatically if present    return { amount: this.cents / 100, currency: "USD" };  }}JSON.stringify({ price: new Money(1999) });// '{"price":{"amount":19.99,"currency":"USD"}}'

Quick Reference

Related APIs and reminders.

  • structuredClone(obj)- Deep-clones an object (handles Dates, Maps, etc.), a better alternative to JSON round-tripping for cloning
  • JSON.stringify(x) === undefined- Happens for undefined, functions, and symbols passed at the top level
  • response.json()- Fetch API helper that parses a Response body as JSON, returns a Promise
  • Content-Type: application/json- Required request header so servers correctly parse a JSON body
  • try/catch around JSON.parse- Mandatory when parsing external or user-supplied strings
Pro Tip

Don't use JSON.parse(JSON.stringify(obj)) to deep-clone objects containing Dates, Maps, Sets, or undefined values -- they'll be silently corrupted or dropped; use structuredClone() instead, which handles all of these correctly.

Was this cheat sheet helpful?

Explore Topics

#JavaScriptJSONHandling#JavaScriptJSONHandlingCheatSheet#Programming#Beginner#JSONStringify#JSONParse#CommonGotchas#CustomSerializationWithToJSON#CheatSheet#SkillVeris