Python TOON (Token-Oriented Object Notation)

0.1.3 · deprecated · verified Thu Apr 16

python-toon is a Python library for encoding and decoding TOON (Token-Oriented Object Notation), a compact data format optimized for Large Language Models (LLMs). It provides bidirectional JSON-to-TOON conversion, aiming to reduce token costs by 30-60% compared to JSON. The current version is 0.1.3, featuring alignment with the official TOON specification (v1.2 for decoding) and command-line interface support. However, users should note that the original `xaviviro/python-toon` repository is officially deprecated in favor of `toon-format/toon-python` as the main community-driven implementation.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `encode` to convert Python dictionaries and lists into TOON format, showcasing both simple objects and tabular arrays. It also shows how to use `decode` to convert a TOON string back into a Python object.

from toon import encode, decode

# Example 1: Encode a simple object
data_object = {"name": "Alice", "age": 30}
toon_output_obj = encode(data_object)
print("Encoded object:\n" + toon_output_obj)
# Expected output for data_object:
# name: Alice
# age: 30

# Example 2: Encode a tabular array (list of uniform objects)
data_list = [
    {"id": 1, "name": "Alice", "active": True},
    {"id": 2, "name": "Bob", "active": False},
    {"id": 3, "name": "Charlie", "active": True}
]
toon_output_list = encode(data_list)
print("\nEncoded tabular list:\n" + toon_output_list)
# Expected output for data_list:
# [3,]{id,name,active}:
# 1,Alice,true
# 2,Bob,false
# 3,Charlie,true

# Example 3: Decode TOON back to Python
toon_string = """users[3]{id,name,role}:
1,Alice,admin
2,Bob,user
3,Charlie,user"""
decoded_data = decode(toon_string)
print("\nDecoded data:")
print(decoded_data)
# Expected output for decoded_data:
# {'users': [{'id': 1, 'name': 'Alice', 'role': 'admin'}, {'id': 2, 'name': 'Bob', 'role': 'user'}, {'id': 3, 'name': 'Charlie', 'role': 'user'}]}

view raw JSON →