JSON.stringify Replacer & JSON.parse Reviver
JSON.stringify Replacer & JSON.parse Reviver
Almost every JavaScript developer uses JSON.stringify(data) and JSON.parse(str). However, few realize that both methods accept a powerful second argument: the Replacer and the Reviver. These transform functions enable masking sensitive fields, formatting custom types, and restoring Date and Map instances during serialization.
1. JSON.stringify() with the Replacer
The syntax for JSON.stringify:
Option A: Replacer as a Function (Filter / Transformer)
The replacer function is called for every key-value pair. Returning undefined omits the property from the output:
Option B: Replacer as an Array (Property Whitelist)
Passing an array of property names acts as an exact whitelist:
2. JSON.parse() with the Reviver
By default, JSON.parse() converts ISO date strings into plain strings. A Reviver function inspects each key-value pair and transforms it back into a native JavaScript object:
3. Serializing BigInt and Custom Types
By default, attempting to serialize a BigInt throws TypeError: Do not know how to serialize a BigInt. A replacer handles this cleanly:
Practice Quiz
Circular Reference Handling & Custom Serialization
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| GraphQL Queries, Mutations & Subscriptions | Circular Reference Handling & Custom Serialization |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.