Use Key Folding to reduce tokens (v1.5)
mainKey folding collapses single-key object chains into dotted paths (e.g., data: { metadata: { items: [...] } } becomes data.metadata.items[...]). This significantly reduces token usage for LLMs.
To use it, enable KeyFoldingMode::Safe in EncodeOptions. You can also limit the depth of folding using with_flatten_depth(n).
Safety Rules: Folding only applies if segments are valid identifiers (a-z, A-Z, 0-9, _), each level has exactly one key, and there are no collisions with sibling keys.
use serde_json::json;
use toon_format::{encode, EncodeOptions, KeyFoldingMode};
let data = json!({
"data": {
"metadata": {
"items": ["a", "b"]
}
}
});
// Enable key folding
let opts = EncodeOptions::new().with_key_folding(KeyFoldingMode::Safe);
let toon = encode(&data, &opts)?;
// Output: data.metadata.items[2]: a,b