Skip to content

TOON API Reference

toon

TOON encoder/decoder — zero dependencies, stdlib only, Python 3.10+.

Part of zerodep: https://github.com/Oaklight/zerodep Copyright (c) 2026 Peng Ding. MIT License.

Drop-in replacement for toon_format core functionality (encode/decode).

TOON is a compact, human-readable serialization format designed for LLM contexts, achieving 30-60% token reduction vs JSON. It combines YAML-like indentation with CSV-like tabular arrays.

Example::

encode({"name": "Alice", "age": 30})
# 'name: Alice

age: 30' decode("name: Alice age: 30") # {'name': 'Alice', 'age': 30}

EncodeOptions

Bases: TypedDict

Options for TOON encoding.

Attributes:

Name Type Description
indent int

Number of spaces per indentation level (default: 2).

delimiter str

Delimiter character for arrays (default: ",").

lengthMarker Union[Literal['#'], Literal[False]]

Marker to prefix array lengths (default: False).

Source code in toon/toon.py
class EncodeOptions(TypedDict, total=False):
    """Options for TOON encoding.

    Attributes:
        indent: Number of spaces per indentation level (default: 2).
        delimiter: Delimiter character for arrays (default: ",").
        lengthMarker: Marker to prefix array lengths (default: False).
    """

    indent: int
    delimiter: str
    lengthMarker: Union[Literal["#"], Literal[False]]

DecodeOptions

Bases: TypedDict

Options for TOON decoding.

Attributes:

Name Type Description
indent int

Number of spaces per indentation level (default: 2).

strict bool

Enable strict validation (default: True).

Source code in toon/toon.py
class DecodeOptions(TypedDict, total=False):
    """Options for TOON decoding.

    Attributes:
        indent: Number of spaces per indentation level (default: 2).
        strict: Enable strict validation (default: True).
    """

    indent: int
    strict: bool

ToonDecodeError

Bases: Exception

Error raised when TOON decoding fails.

Source code in toon/toon.py
class ToonDecodeError(Exception):
    """Error raised when TOON decoding fails."""

encode(value, options=None)

Encode a Python value into TOON format.

Args:
    value: The value to encode (must be JSON-serializable or a supported
        Python type such as datetime, Decimal, set, Path).
    options: Optional encoding options (indent, delimiter, lengthMarker).

Returns:
    TOON-formatted string.

Examples::

    encode({"name": "Alice", "age": 30})
    # 'name: Alice

age: 30' encode([{"id": 1, "name": "A"}, {"id": 2, "name": "B"}]) # '[2,]{id,name}: 1,A 2,B'

Source code in toon/toon.py
def encode(value: Any, options: EncodeOptions | None = None) -> str:
    """Encode a Python value into TOON format.

    Args:
        value: The value to encode (must be JSON-serializable or a supported
            Python type such as datetime, Decimal, set, Path).
        options: Optional encoding options (indent, delimiter, lengthMarker).

    Returns:
        TOON-formatted string.

    Examples::

        encode({"name": "Alice", "age": 30})
        # 'name: Alice\nage: 30'
        encode([{"id": 1, "name": "A"}, {"id": 2, "name": "B"}])
        # '[2,]{id,name}:\n  1,A\n  2,B'
    """
    normalized = _normalize(value)
    opts = _resolve_encode_opts(options)
    w = _Writer(opts.indent)
    _enc_value(normalized, opts, w, 0)
    return w.to_string()

decode(text, options=None)

Decode a TOON-formatted string to a Python value.

Args:
    text: TOON-formatted string.
    options: Optional decoding options (indent, strict).

Returns:
    Decoded Python value.

Raises:
    ToonDecodeError: If the input is malformed.

Examples::

    decode("name: Alice

age: 30") # {'name': 'Alice', 'age': 30} decode("[3]: 1,2,3") # [1, 2, 3]

Source code in toon/toon.py
def decode(text: str, options: DecodeOptions | None = None) -> Any:
    """Decode a TOON-formatted string to a Python value.

    Args:
        text: TOON-formatted string.
        options: Optional decoding options (indent, strict).

    Returns:
        Decoded Python value.

    Raises:
        ToonDecodeError: If the input is malformed.

    Examples::

        decode("name: Alice\nage: 30")
        # {'name': 'Alice', 'age': 30}
        decode("[3]: 1,2,3")
        # [1, 2, 3]
    """
    indent = 2
    strict = True
    if options is not None:
        indent = options.get("indent", 2)
        strict = options.get("strict", True)
    try:
        lines = _scan(text, indent, strict)
    except ToonDecodeError:
        raise
    non_blank = [ln for ln in lines if not ln.is_blank]
    if not non_blank:
        return {}
    first = non_blank[0]
    hdr = _parse_header(first.content)
    if hdr is not None and hdr[0] is None:
        arr, _ = _dec_array_from_hdr(
            lines, 0 if lines[0] == first else lines.index(first), 0, hdr, strict
        )
        return arr
    if len(non_blank) == 1:
        try:
            _split_kv(first.content)
        except ToonDecodeError:
            if hdr is None:
                return _parse_primitive(first.content)
    return _dec_object(lines, 0, 0, strict)