Integration Guide

Learn how to integrate TOON format into your applications using popular programming languages and frameworks. TOON format helps reduce token usage by 30-60% when working with AI language models.

🎯 Dart / Flutter

Use the toon_plus package to encode and decode TOON format in your Flutter/Dart applications.

Install: Add to your pubspec.yaml
dependencies:
  toon_plus: ^0.0.4

Package: pub.dev/packages/toon_plus
import 'package:toon_plus/toon_plus.dart';

void main() {
  // Encode Dart Map to TOON
  final data = {
    'name': 'Alice',
    'age': 30,
    'city': 'New York'
  };
  
  final toonString = ToonEncoder.encode(data);
  print(toonString);
  // Output: name Alice
  //         age 30
  //         city New York
  
  // Decode TOON to Dart Map
  final decoded = ToonDecoder.decode(toonString);
  print(decoded['name']); // Alice
}
Note: The toon_plus package provides full support for encoding Dart objects (Map, List, String, int, double, bool) to TOON format and decoding TOON strings back to Dart objects.

Java

Use JToon to encode and decode TOON format in your Java applications. JToon is available on Maven Central.

Gradle (Groovy DSL):
dependencies {
  implementation 'dev.toonformat:jtoon:1.0.7'
}

Gradle (Kotlin DSL):
dependencies {
  implementation("dev.toonformat:jtoon:1.0.7")
}

Maven:
<dependency>
  <groupId>dev.toonformat</groupId>
  <artifactId>jtoon</artifactId>
  <version>1.0.7</version>
</dependency>
import dev.toonformat.jtoon.JToon;
import java.util.*;

record User(int id, String name, List<String> tags, boolean active, List<?> preferences) {}
record Data(User user) {}

public class ToonExample {
    public static void main(String[] args) {
        User user = new User(123, "Ada", List.of("reading", "gaming"), true, List.of());
        Data data = new Data(user);
        
        System.out.println(JToon.encode(data));
        // Output:
        // user:
        //   id: 123
        //   name: Ada
        //   tags[2]: reading,gaming
        //   active: true
        //   preferences[0]:
    }
}
Note: JToon supports Java records, POJOs, Maps, Lists, and all standard Java types. See the latest version on Maven Central.

🦉 Swift

Use the TOON Swift package for iOS and macOS applications to encode and decode TOON format.

Swift Package Manager: Add to your Package.swift
dependencies: [
  .package(url: "https://github.com/toon-format/toon-swift.git", from: "0.3.0")
]

Then add to your target:
.target(name: "YourTarget", dependencies: ["ToonFormat"])
import ToonFormat

struct User: Codable {
    let id: Int
    let name: String
    let tags: [String]
    let active: Bool
}

// Encoding
let user = User(
    id: 123,
    name: "Ada",
    tags: ["reading", "gaming"],
    active: true
)

let encoder = TOONEncoder()
let data = try encoder.encode(user)
print(String(data: data, encoding: .utf8)!)
// Output:
// id: 123
// name: Ada
// tags[2]: reading,gaming
// active: true

// Decoding
let decoder = TOONDecoder()
let decoded = try decoder.decode(User.self, from: data)
print(decoded.name) // "Ada"

🟢 Node.js

Use the TOON npm package to work with TOON format in your Node.js applications and APIs.

Install: npm install toon-lib
or: yarn add toon-lib
const { encode, decode } = require('toon-lib');
// or: import { encode, decode } from 'toon-lib';

// Encode JavaScript Object to TOON
const data = {
    name: 'Alice',
    age: 30,
    city: 'New York'
};

const toonString = encode(data);
console.log(toonString);
// Output: name Alice
//         age 30
//         city New York

// Decode TOON to JavaScript Object
const decoded = decode(toonString);
console.log(decoded.name); // Alice
Note: The toon-lib package is the same library used by this website. It's available on npm and supports all standard JavaScript data types.

CLI & TypeScript

Use the official TOON CLI tool without installation, or integrate the TypeScript library for type-safe TOON encoding and decoding.

CLI (No Installation Required)

Try TOON instantly with npx:

# Convert JSON to TOON
npx @toon-format/cli input.json -o output.toon

# Pipe from stdin
echo '{"name": "Ada", "role": "dev"}' | npx @toon-format/cli
See the CLI section for all options and examples.

TypeScript Library

npm: npm install @toon-format/toon
pnpm: pnpm add @toon-format/toon
yarn: yarn add @toon-format/toon
import { encode } from '@toon-format/toon'

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

console.log(encode(data))
// Output:
// users[2]{id,name,role}:
//   1,Alice,admin
//   2,Bob,user

Streaming large datasets:

import { encodeLines } from '@toon-format/toon'

const largeData = await fetchThousandsOfRecords()

// Memory-efficient streaming for large data
for (const line of encodeLines(largeData)) {
  process.stdout.write(`${line}\n`)
}

🐍 Python

Use the toon-python package to encode and decode TOON format in your Python applications and AI projects. Includes CLI tools and token counting utilities.

Install from GitHub:
pip install git+https://github.com/toon-format/toon-python.git

Install from source:
git clone https://github.com/toon-format/toon-python.git
cd toon-python
uv sync

Note: Beta published to PyPI - install from source for latest version
from toon_format import encode, decode

# Simple object
encode({"name": "Alice", "age": 30})
# Output:
# name: Alice
# age: 30

# Tabular array (uniform objects)
encode([{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}])
# Output:
# [2,]{id,name}:
#   1,Alice
#   2,Bob

# Decode back to Python
decode("items[2]: apple,banana")
# Output: {'items': ['apple', 'banana']}

CLI Usage

# Auto-detect format by extension
toon input.json -o output.toon      # Encode
toon data.toon -o output.json       # Decode
echo '{"x": 1}' | toon -            # Stdin/stdout

# Options
toon data.json --encode --delimiter "\t" --length-marker
toon data.toon --decode --no-strict --indent 4

# Available options:
# -e/--encode -d/--decode -o/--output
# --delimiter --indent --length-marker --no-strict

API Reference

# encode(value, options=None) → str
encode({"id": 123}, {"delimiter": "\t", "indent": 4, "lengthMarker": "#"})

# Options:
# delimiter: "," (default), "\t", "|"
# indent: Spaces per level (default: 2)
# lengthMarker: "" (default) or "#" to prefix array lengths

# decode(input_str, options=None) → Any
decode("id: 123", {"indent": 2, "strict": True})

# Options:
# indent: Expected indent size (default: 2)
# strict: Validate syntax, lengths, delimiters (default: True)

Token Counting & Comparison

from toon_format import estimate_savings, compare_formats, count_tokens

# Measure savings
data = {"users": [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]}
result = estimate_savings(data)
print(f"Saves {result['savings_percent']:.1f}% tokens")
# Output: Saves 42.3% tokens

# Visual comparison
print(compare_formats(data))
# Output:
# Format Comparison
# ────────────────────────────────────────────────
# Format      Tokens    Size (chars)
# JSON            45             123
# TOON            28              85
# ────────────────────────────────────────────────
# Savings: 17 tokens (37.8%)

# Count tokens directly
toon_str = encode(data)
tokens = count_tokens(toon_str)  # Uses tiktoken (gpt5/gpt5-mini)
# Example: Using TOON with OpenAI API
import openai
from toon_format import encode, estimate_savings

data = {
    'users': [
        {'name': 'Alice', 'role': 'admin'},
        {'name': 'Bob', 'role': 'user'}
    ]
}

# Check token savings before encoding
savings = estimate_savings(data)
print(f"Will save {savings['savings_percent']:.1f}% tokens")

# Convert to TOON to save tokens
toon_data = encode(data)

response = openai.ChatCompletion.create(
    model="gpt-4",
    messages=[
        {"role": "user", "content": f"Process this data: {toon_data}"}
    ]
)
# Using TOON format saves 30-60% on token costs!
← Back to Converter