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 andundefined.- Escape strings properly:
",\\,\n,\r,\t. NaNandInfinitybecomenullin JSON.- Circular references throw
TypeError— use aWeakSetto 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.
