feat: toJSON method support for custom serialization (#237)

* feat: add toJSON method support for custom serialization

* fix: prevent infinite recursion

* test: remove redundant toJSON test cases

* docs: add custom serialization details for toJSON method

* test: fix type issues

---------

Co-authored-by: Johann Schopplich <mail@johannschopplich.com>
This commit is contained in:
Viliam Kopecký
2025-12-04 14:08:56 +01:00
committed by GitHub
parent 7ed9701028
commit a4538b48e7
4 changed files with 189 additions and 0 deletions

View File

@@ -330,4 +330,28 @@ Numbers are emitted in canonical decimal form (no exponent notation, no trailing
Decoders accept both decimal and exponent forms on input (e.g., `42`, `-3.14`, `1e-6`), and treat tokens with forbidden leading zeros (e.g., `"05"`) as strings, not numbers.
### Custom Serialization with toJSON
Objects with a `toJSON()` method are serialized by calling the method and normalizing its result before encoding, similar to `JSON.stringify`:
```ts
const obj = {
data: 'example',
toJSON() {
return { info: this.data }
}
}
encode(obj)
// info: example
```
The `toJSON()` method:
- Takes precedence over built-in normalization (Date, Array, Set, Map)
- Results are recursively normalized
- Is called for objects with `toJSON` in their prototype chain
---
For complete rules on quoting, escaping, type conversions, and strict-mode decoding, see [spec §24 (data model), §7 (strings and keys), and §14 (strict mode)](https://github.com/toon-format/spec/blob/main/SPEC.md).