Skip to main content
The TOONParser class converts TOON format strings into Python data structures (dictionaries, lists, and primitives). It handles indentation parsing, array detection, delimiter recognition, and type conversion.

Constructor

TOONParser(expand_paths: bool = False)
expand_paths
bool
default:"False"
Whether to expand dotted keys (e.g., database.connection.host) into nested objects. When False, dotted keys are preserved as literal key names. This matches the expand_paths option in DecodeOptions.

Example

from toon_json_converter import TOONParser

# Standard parser (dotted keys preserved)
parser = TOONParser()

# Parser with path expansion enabled
parser = TOONParser(expand_paths=True)

Methods

parse

Parse TOON format string into a Python object.
parser.parse(content: str) -> Any
content
str
required
The TOON format string to parse.
return
Any
The parsed Python object. Returns:
  • dict for TOON objects
  • list for TOON arrays
  • Primitives: str, int, float, bool, None
raises
ValueError | KeyError
Raised if the TOON content is malformed or cannot be parsed.

Usage Examples

Basic Object Parsing

from toon_json_converter import TOONParser

parser = TOONParser()

toon_content = """
name: Alice
age: 30
active: true
balance: 1250.5
"""

data = parser.parse(toon_content)
print(data)
Output:
{
    'name': 'Alice',
    'age': 30,
    'active': True,
    'balance': 1250.5
}

Nested Objects

toon_content = """
user:
  name: Alice
  email: [email protected]
status: active
"""

data = parser.parse(toon_content)
print(data)
Output:
{
    'user': {
        'name': 'Alice',
        'email': '[email protected]'
    },
    'status': 'active'
}

Primitive Arrays

toon_content = """
numbers[5]: 1,2,3,4,5
colors[3]: red,green,blue
"""

data = parser.parse(toon_content)
print(data)
Output:
{
    'numbers': [1, 2, 3, 4, 5],
    'colors': ['red', 'green', 'blue']
}

Tabular Arrays

Arrays with field headers are parsed into lists of dictionaries:
toon_content = """
users[3]{name,age,city}:
  Alice,30,NYC
  Bob,25,LA
  Charlie,35,SF
"""

data = parser.parse(toon_content)
print(data)
Output:
{
    'users': [
        {'name': 'Alice', 'age': 30, 'city': 'NYC'},
        {'name': 'Bob', 'age': 25, 'city': 'LA'},
        {'name': 'Charlie', 'age': 35, 'city': 'SF'}
    ]
}

List Arrays

toon_content = """
items[3]:
  - type: book
    title: 1984
  - type: movie
    title: Inception
  - simple string
"""

data = parser.parse(toon_content)
print(data)
Output:
{
    'items': [
        {'type': 'book', 'title': '1984'},
        {'type': 'movie', 'title': 'Inception'},
        'simple string'
    ]
}

Delimiter Detection

The parser automatically detects delimiters from array headers:

Tab Delimiter

toon_content = """
users[2 ]{name,score}:
  Alice\t95
  Bob\t87
"""

data = parser.parse(toon_content)
print(data)
Output:
{
    'users': [
        {'name': 'Alice', 'score': 95},
        {'name': 'Bob', 'score': 87}
    ]
}

Pipe Delimiter

toon_content = "values[3|]: 10|20|30"

data = parser.parse(toon_content)
print(data)
Output:
{'values': [10, 20, 30]}

Length Markers

The parser handles length markers (with # prefix):
toon_content = "items[#5]: 1,2,3,4,5"

data = parser.parse(toon_content)
print(data)
Output:
{'items': [1, 2, 3, 4, 5]}

Path Expansion

When expand_paths=True, dotted keys are expanded into nested objects:
parser = TOONParser(expand_paths=True)

toon_content = "database.connection.host: localhost"

data = parser.parse(toon_content)
print(data)
Output:
{
    'database': {
        'connection': {
            'host': 'localhost'
        }
    }
}
With expand_paths=False (default):
parser = TOONParser(expand_paths=False)

data = parser.parse(toon_content)
print(data)
Output:
{'database.connection.host': 'localhost'}

Quoted Strings

The parser handles quoted strings and unescapes them:
toon_content = """
simple: hello
with_space: "hello world"
number_like: "123"
reserved: "true"
empty: ""
escaped: "Line 1\\nLine 2"
"""

data = parser.parse(toon_content)
print(data)
Output:
{
    'simple': 'hello',
    'with_space': 'hello world',
    'number_like': '123',
    'reserved': 'true',
    'empty': '',
    'escaped': 'Line 1\nLine 2'
}

Special Values

toon_content = """
null_value: null
true_value: true
false_value: false
zero: 0
negative: -42
float: 3.14159
"""

data = parser.parse(toon_content)
print(data)
Output:
{
    'null_value': None,
    'true_value': True,
    'false_value': False,
    'zero': 0,
    'negative': -42,
    'float': 3.14159
}

Complex Nested Structure

toon_content = """
project: TOON Converter
version: 1.0.0
contributors[2]{name,role}:
  Alice,Developer
  Bob,Designer
config:
  debug: false
  features[3]: encoding,decoding,validation
"""

data = parser.parse(toon_content)
print(data)
Output:
{
    'project': 'TOON Converter',
    'version': '1.0.0',
    'contributors': [
        {'name': 'Alice', 'role': 'Developer'},
        {'name': 'Bob', 'role': 'Designer'}
    ],
    'config': {
        'debug': False,
        'features': ['encoding', 'decoding', 'validation']
    }
}

Reading from Files

from toon_json_converter import TOONParser

parser = TOONParser()

# Read TOON file
with open('data.toon', 'r', encoding='utf-8') as f:
    toon_content = f.read()

data = parser.parse(toon_content)
print(data)

Error Handling

from toon_json_converter import TOONParser

parser = TOONParser()

try:
    data = parser.parse(malformed_content)
except (ValueError, KeyError) as e:
    print(f"Parse error: {e}")

Type Detection

The parser automatically detects and converts types:
TOON ValuePython TypeExample
nullNonevalue: nullNone
true / falseboolactive: trueTrue
Integerintcount: 4242
Decimalfloatprice: 19.9919.99
Quoted stringstrname: "Alice"'Alice'
Unquoted stringstrname: Alice'Alice'

Escape Sequences

The parser handles standard escape sequences in quoted strings:
EscapeResult
\\Backslash
\"Double quote
\nNewline
\rCarriage return
\tTab
toon_content = 'message: "Line 1\\nLine 2\\tTabbed"'
data = parser.parse(toon_content)
print(data['message'])
Output:
Line 1
Line 2    Tabbed

Configuration

For more control over parsing behavior, use DecodeOptions with the BidirectionalConverter:
from toon_json_converter import BidirectionalConverter, DecodeOptions

converter = BidirectionalConverter(
    decode_options=DecodeOptions(
        pretty=True,
        indent=4,
        expand_paths=True
    )
)

converter.convert_file('data.toon', 'data.json')

Build docs developers (and LLMs) love