Parsing #1 — Building a Simple JSON.stringify()

Understand the JSON grammar and build a simplified stringify that handles primitives, arrays, objects, and nested structures. Handles circular reference detection.

11 min read
JavaScript
Parsing
JSON
Recursion

TABLE OF CONTENTS
Parsing #1 — Building a Simple JSON.stringify()

JSON.stringify() converts JavaScript values to JSON text. Behind its simple API, it handles objects, arrays, primitives, nested structures, and circular references. This article builds a simplified but functional stringify from scratch.

Prerequisites: Recursion Patterns


1. What JSON.stringify() Handles

JSON supports: objects, arrays, strings, numbers, booleans, and null. It rejects: functions, undefined, Symbols, BigInt, and circular references:

Loading editor...


2. Basic stringify — Primitives, Objects, Arrays

Loading editor...


3. Circular Reference Detection

Loading editor...


4. The toJSON() Method — Custom Serialization

If an object has a toJSON() method, JSON.stringify() calls it:

Loading editor...


5. The replacer Parameter — Filter and Transform

Accepts an array of keys or a transformer function:

Loading editor...


6. Building a Minimal JSON.parse() (Bonus)

JSON parsing is significantly more complex (requires a real parser). Here's a conceptual overview:

Loading editor...


Key Takeaways

  • JSON.stringify() handles primitives, objects, arrays, null — skips functions and undefined.
  • Escape strings properly: ", \\, \n, \r, \t.
  • NaN and Infinity become null in JSON.
  • Circular references throw TypeError — use a WeakSet to detect them.
  • toJSON() lets objects customize serialization.
  • replacer (array or function) filters/transforms during serialization.

Next: Parsing #2 — URL & Query String Parsing — parse query strings into objects and build them back.


Let's Connect

© 2026 Naveen Karthik // Built with React & MUI