JSON: parse, stringify & Common Pitfalls

Difficulty: Beginner

Question

What is JSON? Explain JSON.parse() and JSON.stringify() with their common pitfalls.

Answer

JSON (JavaScript Object Notation) is a lightweight data interchange format. Despite the name, it is language-independent and used widely for API communication and configuration.

Common pitfalls:

  1. undefined, functions, and Symbols are omitted during stringify
  2. NaN and Infinity become null
  3. Date objects become strings (not converted back by parse)
  4. Circular references throw an error
  5. JSON.parse of invalid JSON throws SyntaxError
What a JSON round-trip keeps and drops. Toggle the Date and method under Tweak to see what survives.
  1. stringify flattens to text: Functions and undefined are silently dropped.
  2. Dates become strings: JSON has no Date type; you get an ISO string back.
  3. parse builds new objects: The result is a deep copy of plain data only.

Code examples

Basic Usage

const user = { name: "Alice", age: 25, hobbies: ["coding", "reading"] };

// Stringify
const json = JSON.stringify(user);
console.log(json);
console.log(typeof json);

// Parse
const parsed = JSON.parse(json);
console.log(parsed.name);

// Pretty print with indentation
console.log(JSON.stringify(user, null, 2));

JSON.stringify converts to string, JSON.parse converts back. The third argument of stringify controls indentation.

Pitfalls & Edge Cases

const data = {
  name: "Test",
  fn: function() {},
  undef: undefined,
  nan: NaN,
  inf: Infinity,
  date: new Date("2024-01-01"),
};

console.log(JSON.stringify(data));

// Deep clone trick (with limitations)
const original = { a: 1, b: { c: 2 } };
const clone = JSON.parse(JSON.stringify(original));
clone.b.c = 99;
console.log(original.b.c); // still 2
console.log(clone.b.c);    // 99

Functions, undefined, and Symbols are silently removed. NaN/Infinity become null. The parse+stringify trick creates a deep clone but loses special types.

Key points

Common follow-up questions

Interview tips

Concepts covered

JSON, Serialization, Parsing, Data Exchange

More JavaScript Interview questions