toon_codec

TOON (Token-Oriented Object Notation) encoder/decoder for Gleam.

TOON is a compact, human-readable format for LLM input that reduces token usage compared to JSON while maintaining readability.

This library provides encoding and decoding functions for converting between JSON-like values and TOON format strings.

Quick Start

import toon_codec.{type JsonValue, Object, String, Number}

pub fn main() {
  // Create a JSON value
  let user = Object([
    #("name", String("Alice")),
    #("age", Number(30.0)),
    #("active", Bool(True)),
  ])

  // Encode to TOON
  let toon_str = toon_codec.encode(user)
  // Result: "name: Alice\nage: 30\nactive: true"

  // Decode back to JSON
  case toon_codec.decode(toon_str) {
    Ok(decoded) -> // Process the decoded value
    Error(err) -> // Handle the error
  }
}

Custom Options

import toon_codec.{EncodeOptions, Tab}

let options = EncodeOptions(
  indent: 4,
  delimiter: Tab,
  length_marker: HashMarker,
)

let toon = toon_codec.encode_with_options(value, options)

Encode a JSON value to TOON format with default options.

Default options:

Examples

let value = Object([
  #("name", String("Alice")),
  #("age", Number(30.0)),
])
encode(value)
// -> "name: Alice\nage: 30"

Encode a JSON value to TOON format with custom options.

Examples

let options = EncodeOptions(
  indent: 4,
  delimiter: Tab,
  length_marker: HashMarker,
)
encode_with_options(value, options)

Decode TOON format to JSON value with default options.

Default options:

Examples

decode("name: Alice\nage: 30")
// -> Ok(Object([#("name", String("Alice")), #("age", Number(30.0))]))

Decode TOON format to JSON value with custom options.

Examples

let options = DecodeOptions(indent: 4, strict: False)
decode_with_options(input, options)

Get the default encoding options.

Returns:

Returns:

Types

pub type Delimiter =
  types.Delimiter
pub type JsonValue =
  types.JsonValue
pub type ToonError =
  error.ToonError

Values

pub fn decode(
  input: String,
) -> Result(types.JsonValue, error.ToonError)
pub fn decode_with_options(
  input: String,
  options: types.DecodeOptions,
) -> Result(types.JsonValue, error.ToonError)
pub fn default_decode_options() -> types.DecodeOptions
pub fn default_encode_options() -> types.EncodeOptions
pub fn encode(value: types.JsonValue) -> String
pub fn encode_with_options(
  value: types.JsonValue,
  options: types.EncodeOptions,
) -> String
Search Document