Skip to main content
The 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 = '' and path = [])
  • 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.
Returns: unknown
  • Return the replacement value (will be normalized again)
  • Return undefined to omit the property/element
  • For root value, returning undefined means “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 the path 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:
Performance tips:
  • Keep replacer logic simple and fast
  • Avoid expensive operations (API calls, database queries)
  • Use early returns for common cases
  • Pre-compute lookups outside the replacer

Comparison with JSON.stringify

TOON’s replacer is similar to JSON.stringify’s replacer with key differences:

Error Handling

The replacer function should not throw errors. Return undefined to omit invalid values:
If the replacer throws an error, encoding will fail. Use try-catch inside the replacer if needed.

Examples Repository

For more examples, see: