replacer function provides fine-grained control over TOON encoding, allowing you to transform values, filter properties, add metadata, or customize serialization behavior. It’s similar to JSON.stringify’s replacer parameter but with additional path tracking.
Overview
The replacer function is called for every value during encoding:- The root value (with
key = ''andpath = []) - Every object property (with property name as
key) - Every array element (with string index as
key:'0','1', etc.)
Function Signature
string
required
The property key or array index (as string). Empty string (
'') for the root value.JsonValue
required
The normalized JSON value at this location (after converting to JSON data model).
readonly (string | number)[]
required
Array representing the path from root to this value. Empty array (
[]) for root.unknown
- Return the replacement value (will be normalized again)
- Return
undefinedto omit the property/element - For root value, returning
undefinedmeans “no change” (root cannot be omitted)
Common Use Cases
1. Filtering Sensitive Fields
Remove passwords, tokens, or other sensitive data before encoding:2. Transforming Values
Modify values during encoding (e.g., normalize strings, format numbers):3. Adding Metadata
Inject timestamps, version info, or other metadata at the root:4. Path-Based Filtering
Use thepath parameter to filter based on location in the data structure:
5. Conditional Serialization
Serialize objects differently based on context:6. Type Conversion
Convert dates, BigInts, or other non-JSON types:Note: The replacer receives normalized JSON values, so
Date and BigInt are already converted by the time the replacer sees them. To handle these types, convert them before passing to encode().7. Allowlist Pattern
Only include specific fields:8. Truncating Large Arrays
Limit array sizes to reduce token count:Advanced Patterns
Composing Multiple Replacers
Combine multiple transformations:Logging All Values
Debug encoding by logging every value:Path-Based Transformation
Apply different transformations based on depth:Performance Considerations
The replacer function is called for every value in the data structure:Comparison with JSON.stringify
TOON’s replacer is similar toJSON.stringify’s replacer with key differences:
Error Handling
The replacer function should not throw errors. Returnundefined to omit invalid values:
If the replacer throws an error, encoding will fail. Use try-catch inside the replacer if needed.
