toon

package module
v0.0.0-...-7ca0e27 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2025 License: MIT Imports: 2 Imported by: 0

README

TOON Format for Go

Go Reference Go Report Card

Token-Oriented Object Notation is a compact, human-readable format designed for passing structured data to Large Language Models with significantly reduced token usage.

Example

JSON (verbose):

{
  "users": [
    { "id": 1, "name": "Alice", "role": "admin" },
    { "id": 2, "name": "Bob", "role": "user" }
  ]
}

TOON (compact):

users[2]{id,name,role}:
  1,Alice,admin
  2,Bob,user

Usage

Marshal and Unmarshal
package main

import (
    "fmt"

    "github.com/toon-format/toon-go"
)

type User struct {
    ID    int    `toon:"id"`
    Name  string `toon:"name"`
    Role  string `toon:"role"`
}

type Payload struct {
    Users []User `toon:"users"`
}

func main() {
    in := Payload{
        Users: []User{
            {ID: 1, Name: "Alice", Role: "admin"},
            {ID: 2, Name: "Bob", Role: "user"},
        },
    }

    encoded, err := toon.Marshal(in, toon.WithLengthMarkers(true))
    if err != nil {
        panic(err)
    }
    fmt.Println(string(encoded))

    var out Payload
    if err := toon.Unmarshal(encoded, &out); err != nil {
        panic(err)
    }
    fmt.Printf("first user: %+v\n", out.Users[0])
}
Unmarshal into Maps

Unmarshal can populate dynamic maps, mimicking the encoding/json package:

var doc map[string]any
if err := toon.Unmarshal(encoded, &doc); err != nil {
    panic(err)
}
fmt.Printf("users: %#v\n", doc["users"])
Decode Without Structs

If you do not have a destination struct, use Decode for a dynamic representation:

package main

import (
    "fmt"
    "github.com/toon-format/toon-go"
)

func main() {
    raw := []byte("users[2]{id,name,role}:\n  1,Alice,admin\n  2,Bob,user\n")
    decoded, err := toon.Decode(raw)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%+v\n", decoded)
}

For more runnable samples, explore the programs in ./examples.

Resources

Contributing

Interested in implementing TOON for Go? Check out the specification and feel free to contribute!

License

MIT License © 2025-PRESENT Johann Schopplich

Documentation

Overview

Package toon implements the Token-Oriented Object Notation (TOON) encoder and decoder described in docs/SPEC.md. TOON is a compact, human-readable serialization format targeting LLM workflows where predictable structure and reduced token counts are important. The package exposes a small public API while keeping implementation details inside internal packages.

Index

Constants

View Source
const (
	// DelimiterComma is the default delimiter. It is omitted from brackets.
	DelimiterComma = codec.DelimiterComma
	// DelimiterTab uses HTAB for delimiting values.
	DelimiterTab = codec.DelimiterTab
	// DelimiterPipe uses the '|' character for delimiting values.
	DelimiterPipe = codec.DelimiterPipe
)

Variables

This section is empty.

Functions

func Decode

func Decode(data []byte, opts ...DecoderOption) (any, error)

Decode parses the provided TOON document using a temporary decoder.

func DecodeString

func DecodeString(s string, opts ...DecoderOption) (any, error)

DecodeString parses a TOON document string using a temporary decoder.

func Marshal

func Marshal(v any, opts ...EncoderOption) ([]byte, error)

Marshal renders v into a TOON document using a temporary encoder.

func MarshalString

func MarshalString(v any, opts ...EncoderOption) (string, error)

MarshalString renders v as a TOON document string.

func Unmarshal

func Unmarshal(data []byte, v any, opts ...DecoderOption) error

Unmarshal decodes the TOON document in data into v, which must be a non-nil pointer. Struct fields use `toon` struct tags for naming and omitempty semantics, mirroring Marshal behaviour.

func UnmarshalString

func UnmarshalString(s string, v any, opts ...DecoderOption) error

UnmarshalString decodes the TOON document in s into v.

Types

type Decoder

type Decoder = codec.Decoder

Decoder parses TOON documents into Go values that match the data model from Section 2. Numbers are returned as float64, objects as map[string]any, and arrays as []any. Strings are unescaped per Section 7.1.

func NewDecoder

func NewDecoder(opts ...DecoderOption) *Decoder

NewDecoder constructs a Decoder with the given options.

type DecoderOption

type DecoderOption = codec.DecoderOption

DecoderOption mutates decoder behaviour.

func WithDecoderDocumentDelimiter

func WithDecoderDocumentDelimiter(delimiter Delimiter) DecoderOption

WithDecoderDocumentDelimiter configures the delimiter that influences delimiter-aware string parsing when no array header is active.

func WithDecoderIndent

func WithDecoderIndent(spaces int) DecoderOption

WithDecoderIndent configures the expected indentation step.

func WithStrictMode

func WithStrictMode(strict bool) DecoderOption

WithStrictMode toggles the strict-mode diagnostics.

type Delimiter

type Delimiter = codec.Delimiter

Delimiter identifies the character used to split values inside array scopes.

type Encoder

type Encoder = codec.Encoder

Encoder serializes Go values as TOON documents.

func NewEncoder

func NewEncoder(opts ...EncoderOption) *Encoder

NewEncoder constructs an Encoder using the supplied options. Absent options default to the TOON Core Profile recommendations (Section 19).

type EncoderOption

type EncoderOption = codec.EncoderOption

EncoderOption mutates encoding behaviour.

func WithArrayDelimiter

func WithArrayDelimiter(delimiter Delimiter) EncoderOption

WithArrayDelimiter configures the default delimiter declared for arrays that do not explicitly override the active delimiter.

func WithDocumentDelimiter

func WithDocumentDelimiter(delimiter Delimiter) EncoderOption

WithDocumentDelimiter configures the delimiter that influences quoting decisions outside array scopes.

func WithIndent

func WithIndent(spaces int) EncoderOption

WithIndent configures the number of spaces used per indentation level.

func WithLengthMarkers

func WithLengthMarkers(enabled bool) EncoderOption

WithLengthMarkers enables emitting optional # markers in array headers.

func WithTimeFormatter

func WithTimeFormatter(formatter func(time.Time) string) EncoderOption

WithTimeFormatter specifies the formatter used for time.Time normalization.

type Field

type Field = codec.Field

Field represents a single key/value pair in an ordered object.

type Object

type Object = codec.Object

Object preserves the encounter order of its fields, ensuring deterministic emission by the encoder.

func NewObject

func NewObject(fields ...Field) Object

NewObject constructs an ordered Object from the provided key/value pairs.

Directories

Path Synopsis
examples
basic command
delimiters command
mixedarrays command
normalize command
strictmode command
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL