TOON Format for Rust
Token-Oriented Object Notation (TOON) is a compact, human-readable format designed for passing structured data to Large Language Models with significantly reduced token usage.
This crate provides the official, spec-compliant Rust implementation of TOON v2.0 with v1.5 optional features, offering both a library (toon-format) and a full-featured command-line tool (toon).
Quick Example
JSON (16 tokens, 40 bytes):
TOON (13 tokens, 28 bytes) - 18.75% token savings:
users[2]{id,name}:
1,Alice
2,Bob
Features
- Generic API: Works with any
Serialize/Deserializetype - custom structs, enums, JSON values, and more - Spec-Compliant: Fully compliant with TOON Specification v2.0
- v1.5 Optional Features: Key folding and path expansion
- Safe & Performant: Built with safe, fast Rust
- Powerful CLI: Full-featured command-line tool
- Strict Validation: Enforces all spec rules (configurable)
- Well-Tested: Comprehensive test suite with unit tests, spec fixtures, and real-world scenarios
Installation
As a Library
As a CLI Tool
Library Usage
Basic Encode & Decode
The encode and decode functions work with any type implementing Serialize/Deserialize:
With custom structs:
use ;
use ;
With JSON values:
use ;
use ;
API Reference
Encoding
encode<T: Serialize>(&value, &options) -> Result<String, ToonError>
Encode any serializable type to TOON format. Works with custom structs, enums, collections, and serde_json::Value.
use ;
use json;
let data = json!;
// Default encoding
let toon = encode?;
// items[3]: a,b,c
// Custom delimiter
let opts = new
.with_delimiter;
let toon = encode?;
// items[3|]: a|b|c
// Custom indentation
let opts = new
.with_indent;
let toon = encode?;
EncodeOptions
| Method | Description | Default |
|---|---|---|
with_delimiter(d) |
Set delimiter: Comma, Tab, or Pipe |
Comma |
with_indent(i) |
Set indentation (spaces only) | Spaces(2) |
with_spaces(n) |
Shorthand for Indent::Spaces(n) |
2 |
with_key_folding(mode) |
Enable key folding (v1.5) | Off |
with_flatten_depth(n) |
Set max folding depth | usize::MAX |
Decoding
decode<T: Deserialize>(&input, &options) -> Result<T, ToonError>
Decode TOON format into any deserializable type. Works with custom structs, enums, collections, and serde_json::Value.
With custom structs:
use Deserialize;
use ;
let toon = "host: localhost\nport: 8080";
let config: Config = decode?;
With JSON values:
use Value;
use ;
let toon = "name: Alice\nage: 30";
// Default (strict) decode
let json: Value = decode?;
// Non-strict mode (relaxed validation)
let opts = new.with_strict;
let json: Value = decode?;
// Disable type coercion
let opts = new.with_coerce_types;
let json: Value = decode?;
// With coercion: {"active": true}
// Without: {"active": "true"}
Helper functions:
encode_default<T>(&value)- Encode with default optionsdecode_default<T>(&input)- Decode with default options
DecodeOptions
| Method | Description | Default |
|---|---|---|
with_strict(b) |
Enable strict validation | true |
with_coerce_types(b) |
Auto-convert strings to types | true |
with_expand_paths(mode) |
Enable path expansion (v1.5) | Off |
v1.5 Features
Key Folding (Encoder)
New in v1.5: Collapse single-key object chains into dotted paths to reduce tokens.
Standard nesting:
data:
metadata:
items[2]: a,b
With key folding:
data.metadata.items[2]: a,b
Example:
use json;
use ;
let data = json!;
// Enable key folding
let opts = new
.with_key_folding;
let toon = encode?;
// Output: data.metadata.items[2]: a,b
With Depth Control
let data = json!;
// Fold only 2 levels
let opts = new
.with_key_folding
.with_flatten_depth;
let toon = encode?;
// Output:
// a.b:
// c:
// d: 1
Safety Features
Key folding only applies when:
- All segments are valid identifiers (
a-z,A-Z,0-9,_) - Each level contains exactly one key
- No collision with sibling literal keys
- Within the specified
flatten_depth
Keys like full-name, user.email (if quoted), or numeric keys won't be folded.
Path Expansion (Decoder)
New in v1.5: Automatically expand dotted keys into nested objects.
Compact input:
a.b.c: 1
a.b.d: 2
a.e: 3
Expanded output:
Example:
use Value;
use ;
let toon = "a.b.c: 1\na.b.d: 2";
// Enable path expansion
let opts = new
.with_expand_paths;
let json: Value = decode?;
// {"a": {"b": {"c": 1, "d": 2}}}
Round-Trip Example:
use ;
use ;
let original = json!;
// Encode with folding
let encode_opts = new
.with_key_folding;
let toon = encode?;
// Output: "user.profile.name: Alice"
// Decode with expansion
let decode_opts = new
.with_expand_paths;
let restored: Value = decode?;
assert_eq!; // Perfect round-trip!
Quoted Keys Remain Literal:
use Value;
use ;
let toon = r#"a.b: 1
"c.d": 2"#;
let opts = new
.with_expand_paths;
let json: Value = decode?;
// {
// "a": {"b": 1},
// "c.d": 2 <- quoted key preserved
// }
CLI Usage
Basic Commands
# Auto-detect from extension
# Force mode
# Pipe from stdin
|
|
Encode Options
# Custom delimiter
# Custom indentation
# Key folding (v1.5)
# Show statistics
Decode Options
# Pretty-print JSON
# Relaxed validation
# Disable type coercion
# Path expansion (v1.5)
Full Example
|
| | | | |
+======================================+
| | | | |
||
| ) | | | |
Testing
The library includes a comprehensive test suite covering core functionality, edge cases, spec compliance, and real-world scenarios.
# Run all tests
# Run specific test suites
# With output
Error Handling
All operations return Result<T, ToonError> with descriptive error messages:
use Value;
use ;
match
Error Types
ParseError- Syntax errors with line/column infoLengthMismatch- Array length doesn't match headerTypeMismatch- Unexpected value typeInvalidStructure- Malformed TOON structureSerializationError/DeserializationError- Conversion failures
Examples
Run with cargo run --example examples to see all examples:
structs.rs- Custom struct serializationtabular.rs- Tabular array formattingarrays.rs- Various array formatsarrays_of_arrays.rs- Nested arraysobjects.rs- Object encodingmixed_arrays.rs- Mixed-type arraysdelimiters.rs- Custom delimitersround_trip.rs- Encode/decode round-tripsdecode_strict.rs- Strict validationempty_and_root.rs- Edge cases
Resources
- 📖 TOON Specification v2.0
- 📦 Crates.io Package
- 📚 API Documentation
- 🔧 Main Repository (JS/TS)
- 🎯 Benchmarks & Performance
Contributing
Contributions are welcome! Please see CONTRIBUTING.md for guidelines.
Development
# Clone the repository
# Run tests
# Run lints
# Format code
# Build docs
License
MIT License © 2025-PRESENT Johann Schopplich and Shreyas K S