While JSON.parse() and JSON.stringify() are daily tools for JavaScript developers, their optional parameters unlock powerful capabilities for data transformation and sanitization.
The Reviver Function
JSON.parse() accepts a second argument: a reviver function. This function is called for every key-value pair, allowing you to transform the value before it's returned. This is essential for restoring data types that JSON doesn't support natively, like Date, Map, or Set.
The Replacer Argument
JSON.stringify() accepts a second argument called the replacer. It can be an array of strings (allowlist of keys) or a function. As a function, it works inversely to the reviver, allowing you to filter out sensitive data or transform complex objects before serialization.
Handling Circular References
Standard JSON.stringify() throws an error if it encounters a circular reference. To handle this, you need a custom replacer that tracks visited objects, often using a WeakSet.
Validation and Security
Always wrap JSON.parse() in a try...catch block when dealing with external input, as malformed JSON will throw an error. For structural validation, consider using schema validation libraries like AJV or Zod rather than manual checks.