mirror of
https://github.com/voson-wang/toon.git
synced 2026-01-29 15:24:10 +08:00
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:
@@ -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 §2–4 (data model), §7 (strings and keys), and §14 (strict mode)](https://github.com/toon-format/spec/blob/main/SPEC.md).
|
||||
|
||||
Reference in New Issue
Block a user