TOON Codec Module
zio-blocks-schema-toon is a schema-driven TOON codec module for serializing and deserializing Scala types to and from TOON format. It provides comprehensive encoding and decoding with support for 30 primitive types, records, variants, sequences, maps, and recursive types. Core types: ToonCodec, ToonCodecDeriver, ToonFormat, ToonReader, ToonWriter.
The module integrates with a pure-Scala TOON parser and writer to provide line-oriented, indentation-based serialization that is 30-60% more compact than JSON. TOON (Token-Oriented Object Notation) appears widely across LLM prompts, configuration files, and data exchange where compactness and human readability matter equally.
See also the How to Send Compact Data to an LLM with TOON and Parse the Reply guide, which encodes records as tabular TOON for a prompt and decodes the model's reply into case classes.
Motivation
TOON is a compact, line-oriented text format that encodes the JSON data model with explicit structure and minimal quoting. It appears widely in modern LLM applications, configuration management, and streaming data scenarios where bandwidth and readability are both critical. Manually writing TOON encoders and decoders is error-prone and repetitive, especially for complex types with records, nested structures, and recursive definitions. zio-blocks-schema-toon eliminates this friction by deriving codec instances directly from your Scala types using ZIO Schema. You describe your data shape once, and the module handles:
- Full TOON type support (records, sequences, primitives, null)
- Four array formats: inline (
tags[3]: a,b,c), tabular (users[2]{id,name}:), list (- item), and auto, the default, which picks inline or list from the element type - Automatic schema generation from Scala types
- Customizable field/case name mapping (identity, snake_case, kebab-case, etc.)
- Configurable discriminator strategies for algebraic data types
- Precise error reporting with location traces showing the path to errors
- Recursive type support with automatic cycle detection
- Multiple encoding paths: byte arrays, streams, ByteBuffers, and strings
- Multiple decoding paths: byte arrays, streams, ByteBuffers, and strings
- Cross-platform compatibility (JVM and Scala.js)
Rather than hand-writing TOON parsing logic or relying on external libraries with limited Scala support, you work with strongly-typed schemas that the compiler validates.
Installation
Add the module to your build.sbt:
libraryDependencies += "dev.zio" %% "zio-blocks-schema-toon" % "0.0.56"
For Scala.js, use %%% instead of %%:
libraryDependencies += "dev.zio" %%% "zio-blocks-schema-toon" % "0.0.56"
Supported Scala versions: 2.13.x and 3.x
Introduction
The module provides a complete pipeline for TOON codec derivation and usage:
- Define your type — Any Scala type with a
Schemainstance - Derive a codec — Use
Schema[A].derive(ToonFormat)to obtain aToonCodec[A] - Encode or decode — Call
codec.encode(value)orcodec.decode(toonBytes) - Handle errors —
decodereturns theSchemaError, with the path to the bad value, in aLeft - Customize output — Use
WriterConfigfor indentation and formatting,ReaderConfigfor parsing behavior
The derivation process is automatic for all supported types (all 30 primitives, records, variants, sequences, maps). The module automatically generates TOON-compatible formats and handles encoding/decoding without manual configuration.
How They Work Together
The TOON codec pipeline flows through these layers:
1. User defines Schema[A] for their type
↓
2. Schema[A].derive(ToonFormat) creates ToonCodec[A]
↓
3. ToonCodecDeriver derives Encoder and Decoder implementations
- For primitives: type-specific TOON scalar encoders/decoders
- For records: field-by-field composition with indented nesting
- For variants: union encoding with optional discriminators
- For sequences: one of four formats (auto, inline, tabular, list)
- For maps: record-like encoding with key-value pairs
↓
4. ToonCodec provides multiple encoding paths
- encode(value) → Array[Byte]
- encode(value, output: OutputStream) → Unit
- encode(value, buffer: ByteBuffer) → Unit
- encodeToString(value) → String
↓
5. ToonCodec provides multiple decoding paths
- decode(bytes: Array[Byte]) → Either[SchemaError, A]
- decode(input: InputStream) → Either[SchemaError, A]
- decode(buffer: ByteBuffer) → Either[SchemaError, A]
- decode(toon: String) → Either[SchemaError, A]
↓
6. WriterConfig controls output formatting
- Indentation (default: 2 spaces per level)
- Key folding strategy, delimiter and discriminator field (DynamicValue codec only)
↓
7. ReaderConfig controls parsing behavior
- Strict parsing mode (enforce TOON compliance)
- Path expansion and discriminator field recognition (DynamicValue codec only)
- Array delimiters come from each array's header, not from ReaderConfig
↓
8. Errors include location traces
Shows path (.field.at(index).nested) to error location
A user type flows through the derivation and encoding pipeline as follows:
User type (e.g., case class Person)
↓
Schema.derived (automatic via macro)
↓
Schema[Person].derive(ToonFormat) → ToonCodec[Person]
↓
Use codec.encode(person) to serialize → Array[Byte]
Use codec.decode(toonBytes) to deserialize → Either[SchemaError, Person]
↓
Handle SchemaError with location trace on failure
Type Relationships
ToonCodec[A]— Main public API; contains encoder and decoder for bidirectional serializationToonCodecDeriver— Configuration and derivation system; generates codecs from SchemaToonFormat— Integration with ZIO Schema format system; enablesSchema[A].derive(ToonFormat)WriterConfig— Output formatting configuration (indentation for every codec; delimiter, key folding and discriminator field for theDynamicValuecodec)ReaderConfig— Input parsing configuration (indentation and strict mode for every codec; path expansion and discriminator field for theDynamicValuecodec)ToonReader,ToonWriter— Low-level TOON parsing and serializationNameMapper— Field and case name transformation strategiesArrayFormat— Controls sequence encoding (Inline, Tabular, List, Auto)Delimiter— Specifies separator for inline arrays (Comma, Tab, Pipe)
Common Patterns
This section shows practical patterns for working with TOON codecs in real-world scenarios.
Pattern 1: Derive and Encode a Configuration Record
For a case class with primitive fields, derive a codec and encode to TOON string.
To derive a TOON codec for a record type and encode a value:
import zio.blocks.schema._
import zio.blocks.schema.toon._
case class AppConfig(name: String, port: Int, debug: Boolean)
object AppConfig {
implicit val schema: Schema[AppConfig] = Schema.derived[AppConfig]
}
val codec = AppConfig.schema.derive(ToonFormat)
val config = AppConfig("MyApp", 8080, true)
val toonBytes = codec.encode(config)
// Output:
// name: MyApp
// port: 8080
// debug: true
Pattern 2: Decode TOON with Error Handling
When decoding TOON data, errors include location traces showing where the problem occurred.
To decode TOON and handle errors with location information:
import zio.blocks.schema._
import zio.blocks.schema.toon._
case class DatabaseConfig(host: String, port: Int, username: String)
object DatabaseConfig {
implicit val schema: Schema[DatabaseConfig] = Schema.derived
}
val codec = DatabaseConfig.schema.derive(ToonFormat)
val toon = """
host: localhost
port: invalid
username: admin
"""
val result = codec.decode(toon)
result match {
case Right(config) => println(s"Loaded: $config")
case Left(error) =>
println(s"Error: ${error.getMessage}")
// Error: Expected int, got: invalid at: .port
}
Pattern 3: Work with Arrays in Different Formats
TOON has four formats for encoding sequences, selectable via ArrayFormat (see ArrayFormat). With the default, ArrayFormat.Auto, an array of primitive values is written inline:
import zio.blocks.schema._
import zio.blocks.schema.toon._
case class Tags(items: List[String])
object Tags {
implicit val schema: Schema[Tags] = Schema.derived
}
println(Tags.schema.derive(ToonFormat).encodeToString(Tags(List("scala", "zio", "functional"))))
// items[3]: scala,zio,functional
To encode an array of records as a table, derive the codec with ArrayFormat.Tabular:
import zio.blocks.schema._
import zio.blocks.schema.toon._
case class User(id: Int, name: String)
case class Team(members: List[User])
object User {
implicit val schema: Schema[User] = Schema.derived
}
object Team {
implicit val schema: Schema[Team] = Schema.derived
}
println(
Team.schema
.derive(ToonCodecDeriver.withArrayFormat(ArrayFormat.Tabular))
.encodeToString(Team(List(User(1, "Alice"), User(2, "Bob"))))
)
// members[2]{id,name}:
// 1,Alice
// 2,Bob
Pattern 4: Customize Field Names and Discriminators
Configure the deriver to map field names and control variant encoding.
To derive a codec with custom field name transformation:
import zio.blocks.schema._
import zio.blocks.schema.toon._
case class Person(firstName: String, lastName: String, emailAddress: String)
object Person {
implicit val schema: Schema[Person] = Schema.derived
}
// Use snake_case for field names
val customDeriver = ToonCodecDeriver.withFieldNameMapper(NameMapper.SnakeCase)
val codec = Person.schema.derive(customDeriver)
val person = Person("Alice", "Smith", "alice@example.com")
val toonBytes = codec.encodeToString(person)
// Output:
// first_name: Alice
// last_name: Smith
// email_address: alice@example.com
Pattern 5: Handle Recursive Types
Recursive types (types that reference themselves) are fully supported with automatic cycle detection.
To define and encode a recursive data structure:
import zio.blocks.schema._
import zio.blocks.schema.toon._
sealed trait TreeNode
case class Leaf(value: String) extends TreeNode
case class Branch(label: String, children: List[TreeNode]) extends TreeNode
object TreeNode {
implicit val schema: Schema[TreeNode] = Schema.derived
}
val codec = TreeNode.schema.derive(ToonFormat)
val tree: TreeNode = Branch("root", List(Leaf("a"), Branch("b", List(Leaf("c")))))
val toonBytes = codec.encodeToString(tree)
// Output:
// Branch:
// label: root
// children[2]:
// - Leaf:
// value: a
// - Branch:
// label: b
// children[1]:
// - Leaf:
// value: c
ToonCodec[A]
Main codec type for encoding and decoding values to and from TOON format. Contains encoder and decoder for bidirectional serialization.
Overview
ToonCodec[A] holds both an encoder and decoder, providing a complete solution for serializing and deserializing values in TOON format. The codec is derived automatically from a Schema[A] using ToonFormat.
Encoding Values to Byte Array
Use the codec to convert values to byte arrays:
import zio.blocks.schema._
import zio.blocks.schema.toon._
case class Person(name: String, email: String)
object Person {
implicit val schema: Schema[Person] = Schema.derived
}
val codec = Person.schema.derive(ToonFormat)
val person = Person("Alice", "alice@example.com")
// person: Person = Person(name = "Alice", email = "alice@example.com")
val bytes = codec.encode(person)
// bytes: Array[Byte] = Array(
// 110,
// 97,
// 109,
// 101,
// 58,
// 32,
// 65,
// 108,
// 105,
// 99,
// 101,
// 10,
// 101,
// 109,
// 97,
// 105,
// 108,
// 58,
// 32,
// 97,
// 108,
// 105,
// 99,
// 101,
// 64,
// 101,
// 120,
// 97,
// 109,
// 112,
// 108,
// 101,
// 46,
// 99,
// 111,
// 109
// )
Encoding Values to String
Convert values to human-readable TOON strings:
import zio.blocks.schema._
import zio.blocks.schema.toon._
case class Config(host: String, port: Int)
object Config {
implicit val schema: Schema[Config] = Schema.derived
}
val codec = Config.schema.derive(ToonFormat)
val config = Config("localhost", 8080)
val toonString = codec.encodeToString(config)
Encoding Values to Stream
Write encoded values directly to an output stream:
import zio.blocks.schema._
import zio.blocks.schema.toon._
import java.io.ByteArrayOutputStream
case class Data(timestamp: Long, value: String)
object Data {
implicit val schema: Schema[Data] = Schema.derived
}
val codec = Data.schema.derive(ToonFormat)
val data = Data(System.currentTimeMillis(), "sample")
val output = new ByteArrayOutputStream()
codec.encode(data, output)
val bytes = output.toByteArray
Decoding Values from Byte Array
Use the codec to convert byte arrays back to values:
import zio.blocks.schema._
import zio.blocks.schema.toon._
case class Settings(debug: Boolean, timeout: Int)
object Settings {
implicit val schema: Schema[Settings] = Schema.derived
}
val codec = Settings.schema.derive(ToonFormat)
// Create bytes from a previous encoding
val settings = Settings(debug = true, timeout = 30)
val bytes = codec.encode(settings)
val result: Either[zio.blocks.schema.SchemaError, Settings] = codec.decode(bytes)
Decoding Values from String
Parse and decode values from TOON strings:
import zio.blocks.schema._
import zio.blocks.schema.toon._
case class ServerConfig(name: String, port: Int)
object ServerConfig {
implicit val schema: Schema[ServerConfig] = Schema.derived
}
val codec = ServerConfig.schema.derive(ToonFormat)
val toon = """
name: api-server
port: 8080
"""
val result = codec.decode(toon)
Decoding Values from Stream
Read and decode values from bytes:
import zio.blocks.schema._
import zio.blocks.schema.toon._
case class Message(id: Long, text: String)
object Message {
implicit val schema: Schema[Message] = Schema.derived
}
val codec = Message.schema.derive(ToonFormat)
val message = Message(42, "Hello TOON")
val encoded = codec.encode(message)
val result = codec.decode(encoded)
ToonCodecDeriver
Configuration and derivation system for creating ToonCodec[A] instances from Schema[A].
Overview
ToonCodecDeriver implements the schema-driven derivation of TOON codecs. It automatically handles 30 primitive types and complex types (records, variants, sequences, maps), generating appropriate TOON encoders and decoders with comprehensive customization options.
How Derivation Works
To create a codec from a schema:
import zio.blocks.schema._
import zio.blocks.schema.toon._
case class User(id: Int, name: String, active: Boolean)
object User {
implicit val schema: Schema[User] = Schema.derived
}
val codec = User.schema.derive(ToonFormat)
Primitive Type Support
All 30 primitives of ZIO Blocks Schema are supported:
- Numeric:
Byte,Short,Int,Long,Float,Double,BigInt,BigDecimal - Logical:
Boolean,Char,String - Temporal:
Instant,LocalDate,LocalDateTime,LocalTime,Duration,Period,Year,YearMonth,MonthDay,Month,DayOfWeek,ZonedDateTime,OffsetDateTime,OffsetTime,ZoneId,ZoneOffset - Special:
UUID,Currency,Unit
Record Type Support
Case classes (records) are fully supported. Each field becomes an indented key-value pair in the TOON output:
import zio.blocks.schema._
import zio.blocks.schema.toon._
case class Address(street: String, city: String, zipCode: String)
object Address {
implicit val schema: Schema[Address] = Schema.derived
}
val codec = Address.schema.derive(ToonFormat)
With the default deriver (withTransientEmptyCollection(true)), a record field of type Array[...] is never written, even when the array has elements, so decoding the output gives an empty array and the data is lost silently. List, Vector and Map fields are written as expected, and so is an Array field once you set withTransientEmptyCollection(false). Prefer List or Vector for fields that you encode with this codec.
Variant Type Support
Sealed traits and sum types are encoded as discriminated variants, with customizable discriminator strategies:
import zio.blocks.schema._
import zio.blocks.schema.toon._
sealed trait Status
case class Running(pid: Int) extends Status
case class Stopped(exitCode: Int) extends Status
object Status {
implicit val schema: Schema[Status] = Schema.derived
}
val codec = Status.schema.derive(ToonFormat)
Configuration Methods
To customize derivation behavior, chain configuration methods on ToonCodecDeriver:
To apply field name transformation:
import zio.blocks.schema._
import zio.blocks.schema.toon._
val snakeCaseDeriver = ToonCodecDeriver.withFieldNameMapper(NameMapper.SnakeCase)
To select array format:
import zio.blocks.schema._
import zio.blocks.schema.toon._
val tabularDeriver = ToonCodecDeriver.withArrayFormat(ArrayFormat.Tabular)
To customize variant discriminators:
import zio.blocks.schema._
import zio.blocks.schema.toon._
val fieldDeriver = ToonCodecDeriver.withDiscriminatorKind(DiscriminatorKind.Field("type"))
ToonFormat
Integration point with ZIO Schema's format system. Provides BinaryFormat[ToonCodec] to enable Schema[A].derive(ToonFormat) for any supported type.
Using ToonFormat
To derive a TOON codec using the standard format:
import zio.blocks.schema._
import zio.blocks.schema.toon._
case class Sensor(id: Long, temperature: Double, humidity: Float)
object Sensor {
implicit val schema: Schema[Sensor] = Schema.derived
}
val codec = Sensor.schema.derive(ToonFormat)
ToonFormat is a singleton object extending BinaryFormat[ToonCodec] with the MIME type "text/toon" and the ToonCodecDeriver as its derivation strategy.
WriterConfig
Configuration for TOON output formatting. Controls indentation for every codec, and key folding, the delimiter and the discriminator field for the DynamicValue codec.
Overview
WriterConfig provides predefined configurations and factory methods for customizing TOON serialization output. Every codec reads its indentation; the other settings (key folding, flatten depth, delimiter and discriminator field) apply only to the DynamicValue codec, Schema[DynamicValue].derive(ToonFormat). A codec derived for your own type takes them from ToonCodecDeriver instead.
Indentation Configuration
Control spacing for nested indentation:
import zio.blocks.schema.toon._
val config = WriterConfig.withIndent(4)
// Uses 4 spaces per indentation level (default: 2)
Key Folding Strategy
WriterConfig.withKeyFolding folds a chain of nested single-field records into one dot-separated key. Only the DynamicValue codec reads it; a codec derived for a case class ignores it (see KeyFolding):
import zio.blocks.schema.toon._
val config = WriterConfig.withKeyFolding(KeyFolding.Safe)
WriterConfig.withDelimiter likewise applies only to the DynamicValue codec; a derived codec takes its delimiter from ToonCodecDeriver.withDelimiter (see Delimiter).
Discriminator Field Configuration
WriterConfig.withDiscriminatorField makes the DynamicValue codec write a variant as a record with a discriminator field (_type: Running) instead of a key. A derived codec ignores it; choose its discriminator with ToonCodecDeriver.withDiscriminatorKind (see DiscriminatorKind):
import zio.blocks.schema.toon._
val config = WriterConfig.withDiscriminatorField(Some("_type"))
ReaderConfig
Configuration for TOON input parsing. Controls path expansion and strict parsing mode.
Overview
ReaderConfig provides factory methods for customizing TOON deserialization behavior. It controls whether dot-separated keys expand to nested records and whether parsing is strict.
Path Expansion Configuration
ReaderConfig.withExpandPaths makes the reader turn a dot-separated key such as settings.server.port into nested records. Only the DynamicValue codec reads it; a codec derived for a case class ignores it (see PathExpansion):
import zio.blocks.schema.toon._
val config = ReaderConfig.withExpandPaths(PathExpansion.Safe)
Delimiter Configuration
ReaderConfig.withDelimiter exists, but it has no effect on decoding arrays: the reader takes the delimiter of each array from the array's header, where the writer records any delimiter other than the comma (see Delimiter).
Strict Parsing Mode
Enable or disable strict TOON parsing:
import zio.blocks.schema.toon._
val config = ReaderConfig.withStrict(false)
// Allows lenient parsing (default: true for strict compliance)
ArrayFormat
Controls how sequences are encoded in TOON output.
Overview
ArrayFormat selects one of four strategies for writing sequences: Auto (the default), Inline, Tabular and List. Set it on the deriver with ToonCodecDeriver.withArrayFormat. Inline and Tabular each suit one kind of element; for other elements the codec writes list form instead. Every format keeps the length in the header, so the decoder can check it.
The examples in this section encode the same list of strings and list of records with each format:
import zio.blocks.schema._
import zio.blocks.schema.toon._
case class Tags(items: List[String])
object Tags { implicit val schema: Schema[Tags] = Schema.derived }
case class User(id: Int, name: String)
object User { implicit val schema: Schema[User] = Schema.derived }
case class Team(members: List[User])
object Team { implicit val schema: Schema[Team] = Schema.derived }
val tags = Tags(List("scala", "zio", "functional"))
val team = Team(List(User(1, "Alice"), User(2, "Bob")))
def encodeBoth(format: ArrayFormat): Unit = {
val deriver = ToonCodecDeriver.withArrayFormat(format)
println(Tags.schema.derive(deriver).encodeToString(tags))
println(Team.schema.derive(deriver).encodeToString(team))
}
Inline Format
ArrayFormat.Inline writes an array of primitive values on one line, separated by the delimiter. An array of records is still written in list form:
encodeBoth(ArrayFormat.Inline)
// items[3]: scala,zio,functional
// members[2]:
// - id: 1
// name: Alice
// - id: 2
// name: Bob
Tabular Format
ArrayFormat.Tabular writes an array of records as a table: a header with the field names, then one row per record. An array of primitive values is written in list form:
encodeBoth(ArrayFormat.Tabular)
// items[3]:
// - scala
// - zio
// - functional
// members[2]{id,name}:
// 1,Alice
// 2,Bob
Three known bugs affect tables in 0.0.56. A record with a non-primitive field, such as tags: List[String], is not written in list form as the ArrayFormat.Tabular Scaladoc says; the codec writes a row that it cannot decode (#1778). A top-level List of records written as a table cannot be decoded, even when the same codec wrote it (#1779). And ToonCodecDeriver.withFieldNameMapper is not applied to the field names in a table header (#1780).
List Format
ArrayFormat.List writes every element as a - item on its own line, under a header that keeps the length, such as items[3]::
encodeBoth(ArrayFormat.List)
// items[3]:
// - scala
// - zio
// - functional
// members[2]:
// - id: 1
// name: Alice
// - id: 2
// name: Bob
Auto Format
Auto is the default. It chooses the format from the element type: arrays of primitive values are written inline, and arrays of records are written as lists. The one exception is an array of flat records (records whose fields are all primitives) nested inside a list item, which is written as a table. To write record arrays as tables everywhere, use ArrayFormat.Tabular:
encodeBoth(ArrayFormat.Auto)
// items[3]: scala,zio,functional
// members[2]:
// - id: 1
// name: Alice
// - id: 2
// name: Bob
Delimiter
Specifies the separator character for inline arrays and table rows.
Overview
Delimiter has three values for writing: Comma (the default), Tab and Pipe; a fourth, Delimiter.None, matches no character and is used inside the reader. For a derived codec, set the delimiter with ToonCodecDeriver.withDelimiter. WriterConfig.withDelimiter applies only to the DynamicValue codec, and ReaderConfig.withDelimiter has no effect on decoding arrays.
Available Delimiters
To encode the same tags with each of the three delimiters:
List(Delimiter.Comma, Delimiter.Tab, Delimiter.Pipe).foreach { delimiter =>
println(Tags.schema.derive(ToonCodecDeriver.withDelimiter(delimiter)).encodeToString(tags))
}
// items[3]: scala,zio,functional
// items[3 ]: scala zio functional
// items[3|]: scala|zio|functional
A delimiter other than the comma is written into the array header, as in items[3|]:. The reader takes the delimiter from there, so a codec with the default settings decodes the pipe-separated output:
Tags.schema.derive(ToonFormat).decode("items[3|]: scala|zio|functional")
// res14: Either[SchemaError, Tags] = Right(
// Tags(List("scala", "zio", "functional"))
// )
ToonReader
Low-level, line-oriented text parser implementing TOON format with state management and efficient token scanning.
Overview
ToonReader provides stateful reading of TOON-encoded data with automatic token recognition and error reporting by path (for example at: .port). It handles indentation tracking, quoted string parsing, and numeric value extraction.
Reading from Byte Array
To parse TOON data from a byte array:
import zio.blocks.schema._
import zio.blocks.schema.toon._
case class Person(name: String, age: Int)
object Person { implicit val schema: Schema[Person] = Schema.derived }
val toonBytes = "name: Alice\nage: 30".getBytes("UTF-8")
// Use the codec API for reading (ToonReader is an internal implementation detail)
val codec = Person.schema.derive(ToonFormat)
val result = codec.decode(toonBytes)
Low-Level Parsing
Direct token-by-token parsing for custom scenarios:
import zio.blocks.schema._
import zio.blocks.schema.toon._
// ToonReader is an internal implementation detail of the codec
// Use the public codec API instead:
case class Data(id: Int, name: String)
object Data { implicit val schema: Schema[Data] = Schema.derived }
val codec = Data.schema.derive(ToonFormat)
// Codec provides token-aware parsing and composition for reading
val toonString = "id: 1\nname: test"
val result = codec.decode(toonString)
ToonWriter
Low-level, line-oriented text writer implementing TOON format with optimization for compact representation.
Overview
ToonWriter provides efficient writing of Scala values into TOON text with automatic formatting, indentation, and type-specific encoding.
Writing to Byte Array
To encode values to TOON format:
import zio.blocks.schema.toon._
Custom Encoding Strategies
The writer selects encoding strategies based on value type and configuration:
import zio.blocks.schema.toon._
NameMapper
Transformation strategies for field and case names during encoding and decoding.
Overview
NameMapper provides predefined transformation functions for converting between Scala naming conventions and TOON field names. This enables encoding data with different naming styles without changing your Scala types.
Identity Mapping
Use Scala field names as-is without transformation:
import zio.blocks.schema.toon._
val deriver = ToonCodecDeriver.withFieldNameMapper(NameMapper.Identity)
// firstName → firstName
Snake Case Mapping
Convert camelCase field names to snake_case:
import zio.blocks.schema.toon._
val deriver = ToonCodecDeriver.withFieldNameMapper(NameMapper.SnakeCase)
// firstName → first_name
// emailAddress → email_address
Kebab Case Mapping
Convert camelCase field names to kebab-case:
import zio.blocks.schema.toon._
val deriver = ToonCodecDeriver.withFieldNameMapper(NameMapper.KebabCase)
// firstName → first-name
// emailAddress → email-address
DiscriminatorKind
Controls how variant (sealed trait) discriminators appear in TOON output.
Overview
DiscriminatorKind determines whether variant types are identified by a key discriminator, a field discriminator, or no discriminator at all.
Key Discriminator
Use the variant case name as the TOON key (default):
import zio.blocks.schema.toon._
val deriver = ToonCodecDeriver.withDiscriminatorKind(DiscriminatorKind.Key)
// Running:
// pid: 42
Field Discriminator
Include a dedicated field for the variant type:
import zio.blocks.schema.toon._
val deriver = ToonCodecDeriver.withDiscriminatorKind(DiscriminatorKind.Field("type"))
// type: Running
// pid: 42
No Discriminator
Omit discriminators entirely (for unambiguous contexts):
import zio.blocks.schema.toon._
val deriver = ToonCodecDeriver.withDiscriminatorKind(DiscriminatorKind.None)
// pid: 42
Two known bugs affect DiscriminatorKind.Field and DiscriminatorKind.None. With DiscriminatorKind.Field, a case object of a sealed trait that also has case classes is written as an empty string, with no type: Idle line, so decoding the output fails with Missing discriminator field: type. And a variant stored in a record field is written with its first line on the key's line and its other fields at the level of the parent record, so decoding treats every field after it as part of the variant, and a later field fails with Missing required field. The default DiscriminatorKind.Key round-trips both cases.
KeyFolding
Strategy for folding chains of nested single-field records into dot-separated keys during encoding.
Overview
KeyFolding is set with WriterConfig.withKeyFolding. Only the DynamicValue codec, Schema[DynamicValue].derive(ToonFormat), reads it; a codec derived for a case class ignores it and always writes nested records as indented blocks. Folding follows records that have exactly one field: below, settings holds a record whose only field is server, which holds a record whose only field is port, so the three nested lines become settings.server.port: 8080. A field whose record has two or more fields stays an indented block.
The examples in this section use a shop whose settings nest single-field records:
import zio.blocks.schema._
import zio.blocks.schema.toon._
case class Server(port: Int)
object Server { implicit val schema: Schema[Server] = Schema.derived }
case class Settings(server: Server)
object Settings { implicit val schema: Schema[Settings] = Schema.derived }
case class Shop(name: String, settings: Settings)
object Shop { implicit val schema: Schema[Shop] = Schema.derived }
val shop = Shop("bookshop", Settings(Server(8080)))
val shopValue: DynamicValue = Shop.schema.toDynamicValue(shop)
val dynamicCodec = Schema[DynamicValue].derive(ToonFormat)
val shopCodec = Shop.schema.derive(ToonFormat)
Off (No Folding)
KeyFolding.Off, the default, writes every nested record as an indented block:
println(dynamicCodec.encodeToString(shopValue, WriterConfig.withKeyFolding(KeyFolding.Off)))
// name: bookshop
// settings:
// server:
// port: 8080
Safe Folding
KeyFolding.Safe folds the chain into one dotted key when the DynamicValue codec writes it, while the codec derived for Shop ignores the setting:
println(dynamicCodec.encodeToString(shopValue, WriterConfig.withKeyFolding(KeyFolding.Safe)))
// name: bookshop
// settings.server.port: 8080
println(shopCodec.encodeToString(shop, WriterConfig.withKeyFolding(KeyFolding.Safe)))
// name: bookshop
// settings:
// server:
// port: 8080
PathExpansion
Strategy for parsing dot-separated keys as nested records during decoding.
Overview
PathExpansion is set with ReaderConfig.withExpandPaths and controls whether a key such as settings.server.port is read as nested records or as one key with dots in its name. Like key folding, only the DynamicValue codec reads it. To decode folded TOON into a case class, decode it as a DynamicValue with path expansion, then convert the result with Schema#fromDynamicValue.
The examples below decode this folded document:
val folded = "name: bookshop\nsettings.server.port: 8080"
// folded: String = """name: bookshop
// settings.server.port: 8080"""
Off (No Expansion)
PathExpansion.Off, the default, keeps the dotted key as one field name:
println(dynamicCodec.decode(folded, ReaderConfig.withExpandPaths(PathExpansion.Off)))
// Right({
// name: "bookshop",
// `settings.server.port`: 8080
// })
Safe Expansion
PathExpansion.Safe expands the dotted key into nested records. The codec derived for Shop ignores the setting and fails, but the expanded DynamicValue converts to a Shop:
println(dynamicCodec.decode(folded, ReaderConfig.withExpandPaths(PathExpansion.Safe)))
// Right({
// name: "bookshop",
// settings: {
// server: {
// port: 8080
// }
// }
// })
println(shopCodec.decode(folded, ReaderConfig.withExpandPaths(PathExpansion.Safe)))
// Left(zio.blocks.schema.SchemaError: Missing required field: settings at: .)
println(dynamicCodec.decode(folded, ReaderConfig.withExpandPaths(PathExpansion.Safe)).flatMap(Shop.schema.fromDynamicValue))
// Right(Shop(bookshop,Settings(Server(8080))))
Integration Points
The TOON codec module integrates seamlessly with ZIO Schema and other ZIO Blocks modules:
With ZIO Schema:
- The module uses
Schema[A]to derive codecs automatically - Supports all schema types: primitives, records, variants, sequences, maps, options
- Integrates through the standard
BinaryFormatmechanism
Internal Type Relationships:
ToonCodecDeriverdrives all codec derivation, throughSchema#derive(ToonCodecDeriver)orSchema#derive(ToonFormat)WriterConfigcontrolsToonWriterbehavior during encodingReaderConfigcontrolsToonReaderbehavior during decodingNameMapper,ArrayFormat,Delimiter,DiscriminatorKindall flow throughToonCodecDeriverconfigurationKeyFoldingandPathExpansionaffect how theDynamicValuecodec writes and reads nested records
With Other Modules:
- TOON codecs work alongside other codec modules (JSON, Thrift, YAML, MessagePack) via the format system
- Can be combined with
Schemaevolution utilities for schema versioning - Integrates with
DynamicValuefor generic data handling
Error Handling
TOON decoding errors include location traces showing the path through nested structures where the error occurred.
Understanding Error Traces
Errors render as DynamicOptic paths such as .field.at(0).nested.value: a record field is .name, a sequence index is .at(0), a map value is .atKey(...) and a variant case is .when[Case]. The path shows exactly where decoding failed. Here a list field holds a plain value instead of an array:
import zio.blocks.schema._
import zio.blocks.schema.toon._
case class Team(name: String, members: List[String])
object Team {
implicit val schema: Schema[Team] = Schema.derived
}
val invalidToon = """
name: Engineering
members: invalid
"""
// invalidToon: String = """
// name: Engineering
// members: invalid
// """
Team.schema.derive(ToonFormat).decode(invalidToon) match {
case Right(team) => println(s"Loaded: $team")
case Left(error) => println(s"Error: ${error.getMessage}")
}
// Error: Expected array header with [ at: .members
Zero-Overhead Error Handling
Errors use zero-overhead exceptions (no stack traces) for efficient error reporting in scenarios where errors are expected and handled inline.