---
title: "TOML"
description: "TOML (Tom's Obvious, Minimal Language) is a configuration file format designed to be minimal, readable, and unambiguous. It's commonly used for application configuration, package manifests, and data serialization."
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/cheatsheets/toml
---

# TOML

TOML (Tom's Obvious, Minimal Language) is a human-friendly configuration file format. Designed to be minimal, readable, and unambiguous, it's used extensively in package manifests (like Cargo.toml and pyproject.toml) and application configuration files.

Browse the sections below to explore TOML syntax, data types, and practical configuration examples.

## Getting Started

Fundamental TOML concepts and syntax for beginners.

### Basic Syntax

Comments, whitespace, file format, and basic TOML structure.

**Keywords:** syntax, comments, whitespace, toml, structure

#### Simple TOML file with comments

```toml
# This is a comment
title = "My App"

# Comments can be placed anywhere
version = "1.0.0"
```

_exec_
```bash
toml-parser config.toml
```

_output_
```bash
title: "My App"
version: "1.0.0"
```

A basic TOML file demonstrating key-value pairs and comment usage.

- Comments start with
- Whitespace is ignored in most places.
- Newlines separate key-value pairs.

#### Multi-line structure with sections

```toml
# Configuration file
name = "MyApp"

# Section for database
[database]
host = "localhost"
port = 5432
```

_exec_
```bash
toml-parser config.toml
```

_output_
```bash
name: "MyApp"
database:
  host: "localhost"
  port: 5432
```

Demonstrates basic section structure and organization.

- Sections are defined with [section_name].
- Keys within sections are nested under their section.

**Best practices:**

- Use descriptive key names in lowercase with underscores.
- Add comments to explain non-obvious configuration values.
- Organize related configuration in sections.

**Common errors:**

- **Spaces around the equals sign in key = value**: Keys and values must be separated by '=' with optional spaces: key = value is valid.
- **Missing quotes on string values**: Use quotes for string values, e.g., title = "My App"

### Data Types

Overview of all TOML data types and their representations.

**Keywords:** data types, strings, numbers, booleans, arrays, tables, dates, toml

#### All primitive data types

```toml
# String
name = "Alice"

# Integer
count = 42

# Float
pi = 3.14159

# Boolean
enabled = true

# Date
birth = 1990-05-27

# Time
alarm = 15:30:00

# DateTime
created = 2021-12-25T10:30:00Z
```

_exec_
```bash
toml-parser types.toml
```

_output_
```bash
name: "Alice"
count: 42
pi: 3.14159
enabled: true
birth: 1990-05-27
alarm: 15:30:00
created: 2021-12-25T10:30:00Z
```

Demonstrates each TOML primitive data type with examples.

- TOML supports 7 data types: String, Integer, Float, Boolean, Date, Time, DateTime.
- Type inference is automatic in TOML.

#### Arrays and tables

```toml
# Array
colors = ["red", "green", "blue"]

# Nested array
matrix = [[1, 2], [3, 4]]

# Table
[owner]
name = "Bob"

# Array of tables
[[products]]
id = 1
name = "Widget"
```

_exec_
```bash
toml-parser complex.toml
```

_output_
```bash
colors: ["red", "green", "blue"]
matrix: [[1, 2], [3, 4]]
owner:
  name: "Bob"
products: [{ id: 1, name: "Widget" }]
```

Shows how to define arrays, tables, and arrays of tables.

- Arrays are enclosed in brackets with comma-separated values.
- Tables group related key-value pairs together.

**Best practices:**

- Use lowercase for keys and values when possible.
- Be consistent with date and time formats (use ISO 8601).
- Use descriptive names for array and table keys.

**Common errors:**

- **Mixing data types in an array**: Arrays must contain values of the same type.

### Key-Value Pairs

Syntax for defining keys and values in TOML documents.

**Keywords:** keys, values, toml, assignment, nesting, quoted keys

#### Simple key-value pairs

```toml
name = "Alice"
age = 30
active = true
score = 92.5
```

_exec_
```bash
toml-parser simple.toml
```

_output_
```bash
name: "Alice"
age: 30
active: true
score: 92.5
```

Demonstrates basic key-value pair syntax with different data types.

- Keys are case-sensitive.
- Values must be separated from keys by an equals sign (=).

#### Quoted and dotted keys

```toml
# Quoted key with spaces
"physical address" = "123 Main St"

# Single-quoted key
'special-key' = "value"

# Dotted key (nesting)
database.host = "localhost"
database.port = 5432
database.credentials.user = "admin"
```

_exec_
```bash
toml-parser keys.toml
```

_output_
```bash
physical address: "123 Main St"
special-key: "value"
database:
  host: "localhost"
  port: 5432
  credentials:
    user: "admin"
```

Shows quoted keys and dotted key notation for nesting.

- Quoted keys can contain any character.
- Dotted keys create nested tables automatically.
- Keys must be unique within their scope.

#### Bare and quoted key combinations

```toml
# Bare key (unquoted)
name = "Project"

# Keys with special characters must be quoted
"api-key" = "secret123"
"version 2.0" = true

# Mixed dotted keys
app.settings."user-preferences" = { theme = "dark" }
```

_exec_
```bash
toml-parser mixed.toml
```

_output_
```bash
name: "Project"
api-key: "secret123"
version 2.0: true
app:
  settings:
    user-preferences:
      theme: "dark"
```

Combines bare and quoted keys for flexibility in naming.

- Bare keys can only contain A-Z, a-z, 0-9, -, and _.
- Quote keys if they contain other characters.

**Best practices:**

- Use lowercase, descriptive bare keys when possible.
- Quote keys only when necessary for special characters.
- Use dotted keys to organize related configuration.

**Common errors:**

- **Unquoted key with spaces**: Quote keys that contain spaces, e.g., "my key" = value
- **Duplicate key names**: Ensure each key is unique within its scope.

## Strings

Working with string values in TOML documents.

### Basic Strings

Double-quoted strings with escape sequences and special characters.

**Keywords:** strings, quotes, escape sequences, toml

#### Simple string values

```toml
title = "Hello World"
description = "A simple configuration file"
path = "C:\\Users\\Alice\\Documents"
```

_exec_
```bash
toml-parser strings.toml
```

_output_
```bash
title: "Hello World"
description: "A simple configuration file"
path: "C:\\Users\\Alice\\Documents"
```

Basic string values enclosed in double quotes.

- Strings are enclosed in double quotes.
- Backslashes can be included by escaping them.

#### Escaped characters

```toml
# Common escape sequences
tab = "Column1\tColumn2"
newline = "Line1\nLine2"
quote = "She said \"Hello!\""
backslash = "C:\\path\\to\\file"
unicode = "Café: \u00e9"
```

_exec_
```bash
toml-parser escaped.toml
```

_output_
```bash
tab: "Column1	Column2"
newline: "Line1\nLine2"
quote: "She said \"Hello!\""
backslash: "C:\path\to\file"
unicode: "Café: é"
```

Various escape sequences used in TOML strings.

- Use \t for tabs, \n for newlines, \" for quotes.
- Use \u for 4-digit Unicode escapes, \U for 8-digit.

**Best practices:**

- Use escape sequences for special characters.
- Keep strings readable by breaking long strings into multiple lines with multiline syntax.
- Use raw strings for paths containing backslashes.

**Common errors:**

- **Unescaped quotes inside strings**: Escape quotes with backslash, e.g., \"
- **Literal backslashes not escaped**: Double the backslash, e.g., \\ for a single backslash

### Multiline Strings

Triple-quoted strings for multi-line content with literal or folded modes.

**Keywords:** multiline, strings, triple quotes, toml, folding

#### Multiline basic string

```toml
description = """
This is a multiline
string with multiple
lines of text."""
```

_exec_
```bash
toml-parser multiline.toml
```

_output_
```bash
description: "This is a multiline\nstring with multiple\nlines of text."
```

A basic multiline string using triple double quotes.

- Multiline strings preserve newlines.
- The first newline after the opening quotes is trimmed.
- Escape sequences still work in multiline strings.

#### Multiline literal string

```toml
path = '''
C:\Users\Alice
C:\Users\Bob
'''
```

_exec_
```bash
toml-parser literal.toml
```

_output_
```bash
path: "C:\Users\Alice\nC:\Users\Bob"
```

Literal multiline strings preserve content exactly, no escaping needed.

- Literal strings use triple single quotes.
- No escape sequences are processed in literal strings.
- Useful for paths, JSON, or other literal content.

#### Line folding in multiline strings

```toml
text = """
This is a long line \
that continues \
on the next line."""
```

_exec_
```bash
toml-parser fold.toml
```

_output_
```bash
text: "This is a long line that continues on the next line."
```

Using backslash to fold long lines without adding newlines.

- A backslash at the end of a line continues to the next without adding a newline.
- This helps keep long strings readable.

**Best practices:**

- Use multiline strings for long descriptions or formatted text.
- Use literal multiline strings for paths or code snippets.
- Use line folding to keep long strings readable without breaking them.

**Common errors:**

- **Trying to escape characters in literal strings**: Literal strings don't support escaping; use basic strings if needed.

### String Escape Sequences

All available escape sequences in TOML strings.

**Keywords:** escapes, strings, unicode, special characters, toml

#### Common escape sequences

```toml
backspace = "Back\bspace"
tab = "Tab\there"
linefeed = "Line\nfeed"
form_feed = "Form\ffeed"
carriage_return = "Return\rhere"
quote = "Quote: \"Hello\""
backslash = "Backslash: \\"
```

_exec_
```bash
toml-parser escapes.toml
```

_output_
```bash
backspace: "Back\bspace"
tab: "Tab	here"
linefeed: "Line\nfeed"
form_feed: "Form\ffeed"
carriage_return: "Return\rhere"
quote: "Quote: \"Hello\""
backslash: "Backslash: \"
```

Standard escape sequences for control and special characters.

- \b = backspace (U+0008)
- \t = tab (U+0009)
- \n = line feed (U+000A)
- \f = form feed (U+000C)
- \r = carriage return (U+000D)
- \" = quotation mark (U+0022)
- \\ = backslash (U+005C)

#### Unicode escape sequences

```toml
# 4-digit Unicode escape
emoji = "Smile: \u263A"

# 8-digit Unicode escape
complex = "Mathematical: \U0001D400"

# Mix with characters
text = "Greek: \u03B1\u03B2\u03B3"
```

_exec_
```bash
toml-parser unicode.toml
```

_output_
```bash
emoji: "Smile: ☺"
complex: "Mathematical: 𝐀"
text: "Greek: αβγ"
```

Unicode escapes for 4-digit and 8-digit code points.

- \uXXXX for 4-digit Unicode escapes (U+0000 to U+FFFF)
- \UXXXXXXXX for 8-digit Unicode escapes (U+00000000 to U+7FFFFFFF)
- Use for emoji and special characters not easily typed.

**Best practices:**

- Use \n for line breaks instead of literal newlines when readability is important.
- Use \u and \U for characters not easily typed on your keyboard.
- Keep escape sequences simple; use literal strings when possible.

**Common errors:**

- **Using wrong escape sequence**: Ensure you use the correct sequence (e.g., \n for newline, not \l).
- **Invalid Unicode code point**: Verify the Unicode value is within the valid range.

## Tables and Nesting

Defining and organizing tables in TOML documents.

### Basic Tables

Simple table headers, dot-separated keys, and subtables.

**Keywords:** tables, headers, nesting, sections, toml

#### Simple table definition

```toml
[owner]
name = "Alice"
email = "alice@example.com"

[database]
host = "localhost"
port = 5432
```

_exec_
```bash
toml-parser tables.toml
```

_output_
```bash
owner:
  name: "Alice"
  email: "alice@example.com"
database:
  host: "localhost"
  port: 5432
```

Defines two tables with their respective key-value pairs.

- Tables are headers enclosed in brackets [table_name].
- Keys after a table belong to that table.
- Whitespace in table names is allowed only in quoted names.

#### Nested tables with dot notation

```toml
# Using dot notation for subtables
database.connection.host = "localhost"
database.connection.port = 5432
database.connection.ssl = true

[database.credentials]
user = "admin"
password = "secret"
```

_exec_
```bash
toml-parser nested.toml
```

_output_
```bash
database:
  connection:
    host: "localhost"
    port: 5432
    ssl: true
  credentials:
    user: "admin"
    password: "secret"
```

Shows both dot notation and explicit table headers for nesting.

- Dotted keys create nested tables automatically.
- Can mix dotted keys with explicit table headers.
- Parent tables are created automatically if needed.

#### Nested subtables

```toml
[server]
host = "0.0.0.0"
port = 8080

[server.ssl]
enabled = true
cert = "/path/to/cert"

[server.ssl.options]
min_version = "TLSv1.2"
```

_exec_
```bash
toml-parser subtables.toml
```

_output_
```bash
server:
  host: "0.0.0.0"
  port: 8080
  ssl:
    enabled: true
    cert: "/path/to/cert"
    options:
      min_version: "TLSv1.2"
```

Hierarchical nesting of tables using bracket notation.

- [parent.child] defines subtables of parent.
- Each table must be defined only once (no redefinition).

**Best practices:**

- Use descriptive table names in lowercase.
- Group related configuration into tables.
- Use dot notation for simple nested values, explicit headers for complex sections.

**Common errors:**

- **Redefining a table header**: Define each table only once; use dotted keys if you need to add more values later.
- **Mixing key and table for the same name**: A name cannot be both a key and a table header in the same scope.

### Array of Tables

Using [[array.of.tables]] syntax for multiple table items.

**Keywords:** arrays, tables, multiple items, toml, brackets

#### Simple array of tables

```toml
[[products]]
id = 1
name = "Widget"
price = 9.99

[[products]]
id = 2
name = "Gadget"
price = 19.99
```

_exec_
```bash
toml-parser array_tables.toml
```

_output_
```bash
products:
  - id: 1
    name: "Widget"
    price: 9.99
  - id: 2
    name: "Gadget"
    price: 19.99
```

Creates an array of table elements with multiple items.

- [[table_name]] appends a new table to an array.
- Each [[table_name]] block creates a new element.
- All elements have the same structure.

#### Nested array of tables

```toml
[package]
name = "my-package"

[[package.dependencies]]
name = "requests"
version = "2.28.0"

[[package.dependencies]]
name = "flask"
version = "2.0.0"
```

_exec_
```bash
toml-parser nested_array.toml
```

_output_
```bash
package:
  name: "my-package"
  dependencies:
    - name: "requests"
      version: "2.28.0"
    - name: "flask"
      version: "2.0.0"
```

Array of tables nested within a parent table.

- [[parent.child]] creates an array within the parent table.
- Each child table is a separate element in the array.

#### Multiple arrays of tables

```toml
[[users]]
name = "Alice"
role = "admin"

[[users]]
name = "Bob"
role = "user"

[[projects]]
title = "Project A"
owner = "Alice"

[[projects]]
title = "Project B"
owner = "Bob"
```

_exec_
```bash
toml-parser multiple_arrays.toml
```

_output_
```bash
users:
  - name: "Alice"
    role: "admin"
  - name: "Bob"
    role: "user"
projects:
  - title: "Project A"
    owner: "Alice"
  - title: "Project B"
    owner: "Bob"
```

Multiple independent arrays of tables in the same document.

- Each [[name]] creates a separate array.
- Arrays can be defined independently.

**Best practices:**

- Use array of tables for lists of similar items.
- Keep table items small and focused.
- Use descriptive key names within each table element.

**Common errors:**

- **Inconsistent structure in array elements**: All elements in an array should have the same structure.
- **Missing [[brackets]] for array items**: Use [[name]] for arrays, not just [name].

### Nested Structures

Complex deeply nested tables and hierarchical data.

**Keywords:** nested, hierarchical, complex, deep nesting, toml

#### Deeply nested tables

```toml
[server.http.handlers.api]
endpoint = "/api/v1"
timeout = 30

[server.http.handlers.websocket]
endpoint = "/ws"
timeout = 0

[server.https.ssl]
cert = "/path/to/cert"
key = "/path/to/key"
```

_exec_
```bash
toml-parser deep_nesting.toml
```

_output_
```bash
server:
  http:
    handlers:
      api:
        endpoint: "/api/v1"
        timeout: 30
      websocket:
        endpoint: "/ws"
        timeout: 0
  https:
    ssl:
      cert: "/path/to/cert"
      key: "/path/to/key"
```

Demonstrates multiple levels of nesting with different branches.

- TOML supports unlimited nesting depth.
- Use clear naming to avoid confusion in deeply nested structures.
- Dotted keys can simplify defining deeply nested values.

#### Complex hierarchical structure

```toml
[app]
name = "MyApp"
version = "1.0.0"

[app.features]
auth = true
api = true
websocket = false

[[app.features.modules]]
name = "Auth"
enabled = true

[[app.features.modules]]
name = "API"
enabled = true

[app.logging]
level = "info"
format = "json"
```

_exec_
```bash
toml-parser complex_nested.toml
```

_output_
```bash
app:
  name: "MyApp"
  version: "1.0.0"
  features:
    auth: true
    api: true
    websocket: false
    modules:
      - name: "Auth"
        enabled: true
      - name: "API"
        enabled: true
  logging:
    level: "info"
    format: "json"
```

Combines tables, arrays of tables, and nested structures.

- Mix different structure types for flexibility.
- Organize by functionality or domain.

**Best practices:**

- Keep nesting to reasonable depth (3-4 levels typically).
- Use clear, intuitive naming for parent tables.
- Document complex structures with comments.

**Common errors:**

- **Overly deep nesting causing readability issues**: Consider flattening some levels or using dotted keys.
- **Forgetting parent table context in arrays**: Use [[parent.child]] syntax correctly.

## Data Types

Detailed coverage of TOML data types and representations.

### Numbers

Integers, floats, scientific notation, and underscores in numbers.

**Keywords:** numbers, integers, floats, scientific notation, underscore, toml

#### Integer number formats

```toml
# Decimal integers
count = 42
negative = -17

# Hexadecimal (0x prefix)
hex_value = 0xDEADBEEF

# Octal (0o prefix)
octal = 0o755

# Binary (0b prefix)
binary = 0b11010110
```

_exec_
```bash
toml-parser integers.toml
```

_output_
```bash
count: 42
negative: -17
hex_value: 3735928559
octal: 493
binary: 214
```

TOML supports decimal, hexadecimal, octal, and binary integers.

- Integers are 64-bit signed numbers.
- Leading zeros are not allowed in decimal notation.
- Hex, octal, and binary integers have specific prefixes.

#### Float number formats

```toml
# Standard float
pi = 3.14159

# Negative float
temperature = -40.0

# Scientific notation
large = 5e+22
small = 1.47e-12

# Special float values
infinity = inf
neg_infinity = -inf
not_number = nan
```

_exec_
```bash
toml-parser floats.toml
```

_output_
```bash
pi: 3.14159
temperature: -40.0
large: 5e+22
small: 1.47e-12
infinity: Infinity
neg_infinity: -Infinity
not_number: NaN
```

TOML supports standard floats, scientific notation, and special values.

- Floats are 64-bit (IEEE 754 double precision).
- Scientific notation uses 'e' or 'E'.
- Special values inf, -inf, nan represent infinity and NaN.

#### Numbers with underscores

```toml
# Readable large numbers
million = 1_000_000
phone = 555_123_4567
binary = 0b1010_1010

# Floats with underscores
pi = 3.14_159_265
scientific = 1.602_176_634e-19
```

_exec_
```bash
toml-parser underscores.toml
```

_output_
```bash
million: 1000000
phone: 5551234567
binary: 170
pi: 3.14159265
scientific: 1.602176634e-19
```

Underscores improve readability of large numbers.

- Underscores can be placed between digits for readability.
- Leading/trailing underscores are not allowed.
- Underscores are ignored during parsing.

**Best practices:**

- Use underscores in large numbers for readability.
- Be consistent with notation (all hex, all decimal, etc.).
- Use scientific notation for very large or small values.

**Common errors:**

- **Leading zeros in decimal integers**: Use hex/octal/binary notation for numbers with prefixes.
- **Underscores at start or end of number**: Underscores can only appear between digits.

### Booleans and Null

Boolean true/false values and null representation in TOML.

**Keywords:** booleans, true, false, , toml

#### Boolean values

```toml
# Boolean values are lowercase
enabled = true
debug = false

[features]
auth = true
logging = false
updates = true
```

_exec_
```bash
toml-parser booleans.toml
```

_output_
```bash
enabled: true
debug: false
features:
  auth: true
  logging: false
  updates: true
```

TOML uses lowercase true and false for boolean values.

- Boolean values are lowercase (true, false).
- No yes/no or on/off alternatives in TOML.
- Booleans are distinct from strings.

#### Representing null or absence

```toml
# TOML doesn't have a native null type
# Options for representing absence:

# 1. Omit the key entirely
# optional_field = (not present)

# 2. Use empty string
empty = ""

# 3. Use special marker values
null_marker = "null"
unset = "unset"
none = "none"
```

_exec_
```bash
toml-parser null.toml
```

_output_
```bash
empty: ""
null_marker: "null"
unset: "unset"
none: "none"
```

TOML doesn't have a null type; use conventions or omit keys.

- TOML does not have a native null or None value.
- Omit the key entirely to represent absence.
- Use empty string or special marker strings if needed.

**Best practices:**

- Use boolean values for on/off or enabled/disabled settings.
- Omit optional keys rather than using null-like values.
- Document how absence is represented in your TOML files.

**Common errors:**

- **Using True or False (capitalized)**: Use lowercase true and false.
- **Trying to use null or None**: TOML doesn't support null; omit the key or use "null" string.

**Advanced notes:**

- **Handling Optional Values:** Consider using a separate section to list which keys are optional.

### Dates and Times

ISO 8601 formatted dates, times, and datetimes with timezone support.

**Keywords:** dates, times, datetime, ISO 8601, timezone, toml

#### Date and time formats

```toml
# Date (RFC 3339 profile of ISO 8601)
birthday = 1990-05-27

# Time (no date)
alarm = 15:30:00

# Local DateTime (date and time, no timezone)
meeting = 2021-12-25T10:30:00
```

_exec_
```bash
toml-parser dates.toml
```

_output_
```bash
birthday: 1990-05-27
alarm: 15:30:00
meeting: 2021-12-25T10:30:00
```

Basic date, time, and local datetime formats in ISO 8601.

- Dates follow YYYY-MM-DD format.
- Times follow HH:MM:SS or HH:MM:SS.ffffff format.
- LocalDateTime combines date and time without timezone.

#### Datetime with timezone

```toml
# UTC timezone (Z suffix)
created = 2021-12-25T10:30:00Z

# With offset
eastern = 2021-12-25T10:30:00-05:00

# With positive offset
tokyo = 2021-12-25T10:30:00+09:00

# Milliseconds precision
precise = 2021-12-25T10:30:00.123Z
```

_exec_
```bash
toml-parser datetimes.toml
```

_output_
```bash
created: 2021-12-25T10:30:00Z
eastern: 2021-12-25T10:30:00-05:00
tokyo: 2021-12-25T10:30:00+09:00
precise: 2021-12-25T10:30:00.123Z
```

Datetime values with timezone information and fractional seconds.

- Z suffix indicates UTC (Zulu) time.
- Offset format is ±HH:MM.
- Fractional seconds support up to nanosecond precision.

**Best practices:**

- Use ISO 8601 format consistently throughout your TOML files.
- Use Z for UTC times; include offset for other timezones.
- Include timezone information for important timestamps.

**Common errors:**

- **Using non-ISO 8601 date formats**: Always use YYYY-MM-DD format for dates.
- **Missing timezone information in datetimes**: Add Z for UTC or ±HH:MM for other timezones.

**Advanced notes:**

- **Time Precision:** Fractional seconds can include up to nanosecond precision (9 digits).

## Advanced Features

Advanced TOML features for complex configurations.

### Inline Tables

Compact single-line table syntax with {key = value} format.

**Keywords:** inline, tables, compact, single-line, toml

#### Simple inline table

```toml
point = { x = 1, y = 2 }
color = { r = 255, g = 128, b = 0 }
person = { name = "Alice", age = 30 }
```

_exec_
```bash
toml-parser inline.toml
```

_output_
```bash
point:
  x: 1
  y: 2
color:
  r: 255
  g: 128
  b: 0
person:
  name: "Alice"
  age: 30
```

Inline tables provide a compact way to define tables on a single line.

- Inline tables are enclosed in curly braces.
- Keys and values are separated by equals with optional spaces.
- Inline tables cannot span multiple lines.

#### Nested inline tables

```toml
# Inline table containing inline table
config = {
  database = { host = "localhost", port = 5432 },
  cache = { host = "redis", ttl = 3600 }
}

# Array of inline tables
points = [
  { x = 0, y = 0 },
  { x = 1, y = 2 },
  { x = 3, y = 4 }
]
```

_exec_
```bash
toml-parser nested_inline.toml
```

_output_
```bash
config:
  database:
    host: "localhost"
    port: 5432
  cache:
    host: "redis"
    ttl: 3600
points:
  - x: 0
    y: 0
  - x: 1
    y: 2
  - x: 3
    y: 4
```

Inline tables can be nested and used in arrays.

- Inline tables cannot be redefined or extended later.
- Useful for simple, fixed data structures.

**Best practices:**

- Use inline tables for simple, fixed structures.
- Keep inline tables concise and readable.
- Use regular tables for complex or frequently updated structures.

**Common errors:**

- **Trying to extend an inline table**: Inline tables are immutable and cannot be modified later.
- **Multi-line inline table**: Inline tables must be on a single line.

### Advanced DateTime

Offset datetimes, local datetimes, and time precision handling.

**Keywords:** datetime, timezone, offset, precision, local, toml

#### All datetime variants

```toml
# Offset DateTime (with timezone)
utc_time = 2021-12-25T10:30:00Z
eastern_time = 2021-12-25T10:30:00-05:00

# Local DateTime (no timezone)
local_meeting = 2021-12-25T10:30:00

# Local Date (no time)
deadline = 2021-12-31

# Local Time (no date)
opening_time = 09:00:00
```

_exec_
```bash
toml-parser all_datetime.toml
```

_output_
```bash
utc_time: 2021-12-25T10:30:00Z
eastern_time: 2021-12-25T10:30:00-05:00
local_meeting: 2021-12-25T10:30:00
deadline: 2021-12-31
opening_time: 09:00:00
```

Examples of all TOML datetime type variants.

- Offset DateTime includes timezone information.
- Local DateTime is timezone-naive.
- Local Date and Local Time can exist independently.

#### Fractional seconds and precision

```toml
# Milliseconds
ms_precision = 2021-12-25T10:30:00.123Z

# Microseconds
us_precision = 2021-12-25T10:30:00.123456Z

# Nanoseconds
ns_precision = 2021-12-25T10:30:00.123456789Z

# Trailing zeros
long_precision = 2021-12-25T10:30:00.1Z
```

_exec_
```bash
toml-parser precision.toml
```

_output_
```bash
ms_precision: 2021-12-25T10:30:00.123Z
us_precision: 2021-12-25T10:30:00.123456Z
ns_precision: 2021-12-25T10:30:00.123456789Z
long_precision: 2021-12-25T10:30:00.1Z
```

Demonstrates various precision levels in fractional seconds.

- Fractional seconds are optional and can be 1-9 digits.
- No precision loss; values are preserved as specified.

**Best practices:**

- Use UTC time (Z) for server logs and critical timestamps.
- Include timezone offset for user-facing timestamps.
- Use local datetime for scheduling without timezone sensitivity.

**Common errors:**

- **Invalid timezone offset format**: Use ±HH:MM format, e.g., -05:00, not -5:00 or -0500.
- **Missing fractional seconds in precise times**: Include fractional seconds if they're important for your use case.

### Comments and Formatting

Effective commenting and formatting practices in TOML.

**Keywords:** comments, formatting, style, readability, organization, toml

#### Effective commenting

```toml
# Main application configuration
# Last updated: 2025-02-28

title = "MyApp"  # Application title
version = "1.0.0"

# Database connection settings
[database]
host = "localhost"  # Database server hostname
port = 5432         # Standard PostgreSQL port
ssl = true          # Enable SSL for secure connections
```

_exec_
```bash
toml-parser commented.toml
```

_output_
```bash
title: "MyApp"
version: "1.0.0"
database:
  host: "localhost"
  port: 5432
  ssl: true
```

Shows effective use of comments for documentation.

- Comments start with
- Inline comments are allowed after values.
- Comments help clarify non-obvious configuration.

#### Organized file structure

```toml
# ============================================================================
# Application Configuration
# ============================================================================

[metadata]
name = "MyApp"
version = "1.0.0"
author = "Team"

# ============================================================================
# Server Configuration
# ============================================================================

[server]
host = "0.0.0.0"
port = 8080

[server.ssl]
enabled = true
cert = "/path/to/cert"

# ============================================================================
# Database Configuration
# ============================================================================

[database]
url = "postgresql://localhost/mydb"
```

_exec_
```bash
toml-parser organized.toml
```

_output_
```bash
metadata:
  name: "MyApp"
  version: "1.0.0"
  author: "Team"
server:
  host: "0.0.0.0"
  port: 8080
  ssl:
    enabled: true
    cert: "/path/to/cert"
database:
  url: "postgresql://localhost/mydb"
```

Well-organized file structure with clear section headers.

- Use visual separators (comment lines) for clarity.
- Group related configurations into sections.
- Maintain consistent formatting throughout the file.

**Best practices:**

- Start files with a header comment explaining the purpose.
- Add inline comments for non-obvious values.
- Use visual separators between major sections.
- Keep comments current with the configuration.

**Common errors:**

- **Over-commenting obvious values**: Comment only when the purpose isn't clear from the key name.
- **Outdated comments that don't match the configuration**: Update comments when configuration changes.

## Best Practices

Best practices for writing effective TOML configurations.

### Common Patterns

Patterns used in real-world TOML files and package manifests.

**Keywords:** patterns, cargo, pyproject, config, standards, examples, toml

#### Cargo.toml (Rust) style

```toml
[package]
name = "my-app"
version = "0.1.0"
edition = "2021"
description = "My awesome application"
authors = ["Me <me@example.com>"]

[dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.0", features = ["full"] }

[dev-dependencies]
pytest = "0.13"

[profile.release]
opt-level = 3
```

_exec_
```bash
cargo build
```

Standard structure of Cargo.toml for Rust projects.

- [package] section contains metadata.
- [dependencies] lists production dependencies.
- [dev-dependencies] for testing dependencies.
- Feature specifications are common.

#### pyproject.toml (Python) style

```toml
[project]
name = "my-package"
version = "0.1.0"
description = "A Python package"
authors = [{name = "Alice", email = "alice@example.com"}]
requires-python = ">=3.8"

[project.dependencies]
requests = ">=2.0"
flask = ">=2.0"

[build-system]
requires = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta"
```

_exec_
```bash
pip install .
```

Standard structure of pyproject.toml for Python projects.

- [project] contains package metadata.
- Author details use inline table format.
- [build-system] specifies build requirements.

#### Application config file pattern

```toml
# [app.toml] - Server configuration
[app]
name = "MyService"
environment = "production"
debug = false

[server]
host = "0.0.0.0"
port = 8080
workers = 4

[database]
url = "postgresql://user:pass@localhost/db"
pool_size = 20

[logging]
level = "info"
format = "json"
file = "/var/log/myservice.log"

[[services]]
name = "auth"
url = "http://auth-service:8000"

[[services]]
name = "cache"
url = "redis://localhost:6379"
```

_exec_
```bash
myapp --config app.toml
```

Typical application configuration file structure.

- Metadata in [app] section.
- Server/database settings in dedicated sections.
- External services in array of tables.

**Best practices:**

- Follow established patterns for your project type.
- Use consistent naming conventions throughout.
- Group related settings into sections.
- Include version and author information where appropriate.

**Common errors:**

- **Inventing custom patterns instead of following standards**: Follow established patterns for Cargo.toml, pyproject.toml, etc.
- **Inconsistent key naming across configuration**: Establish and follow a naming convention consistently.

### Readability and Style

Organizing keys and maintaining consistent formatting.

**Keywords:** readability, style, organization, formatting, naming, conventions, toml

#### Well-organized TOML file

```toml
# Services Configuration
# Well-organized with logical grouping

[metadata]
version = "1.0.0"
updated = 2025-02-28

[api]
# Core API settings
host = "0.0.0.0"
port = 8000
timeout = 30

[api.auth]
# Authentication configuration
enabled = true
jwt_secret = "your-secret-key"
token_expire_hours = 24

[api.cors]
# CORS settings
allowed_origins = ["http://localhost:3000"]
allowed_methods = ["GET", "POST", "PUT"]

[database]
host = "localhost"
port = 5432
name = "myapp"
pool_size = 20

[logging]
level = "info"
format = "json"
```

_exec_
```bash
app --config config.toml
```

Configuration organized for clarity and maintainability.

- Use descriptive section names.
- Add comments explaining purpose of sections.
- Keep related items grouped together.
- Use consistent indentation (though not required).

#### Naming conventions

```toml
# ✓ Good naming conventions
[database]
connection_timeout = 10
max_pool_size = 20
retry_attempts = 3

[cache]
redis_host = "localhost"
redis_port = 6379
ttl_seconds = 3600

[service]
api_key = "secret"
api_version = "v1"
api_timeout = 30
```

_exec_
```bash
app --validate-config
```

_output_
```bash
Configuration is valid
```

Demonstrates consistent naming conventions.

- Use snake_case for key names.
- Use descriptive suffixes (_host, _port, _timeout, etc.).
- Keep names consistent across similar settings.
- Avoid ambiguous abbreviations.

**Best practices:**

- Use snake_case for all keys.
- Group related settings under the same table.
- Add section comments explaining purpose.
- Order sections logically (metadata, core settings, optional).

**Common errors:**

- **Inconsistent key naming (camelCase vs snake_case)**: Use snake_case consistently throughout.
- **Poor organization making files hard to navigate**: Group related settings and add comments.

**Advanced notes:**

- **Configuration Validation:** Consider tools that validate TOML structure against a schema.

### Validation and Usage

Loading and parsing TOML files in programming languages.

**Keywords:** parsing, loading, validation, libraries, examples, languages, toml

#### Python - Loading TOML with tomllib

```toml
[app]
name = "MyApp"
debug = false

[database]
url = "postgresql://localhost/myapp"
pool_size = 20
```

_exec_
```python
import tomllib

with open('config.toml', 'rb') as f:
    config = tomllib.load(f)

print(config['app']['name'])
print(config['database']['pool_size'])
```

_output_
```bash
MyApp
20
```

Python example using the built-in tomllib module (Python 3.11+).

- tomllib requires opened file in binary mode ('rb').
- For older Python, use the 'tomli' package.
- Returns a dictionary with nested structure.

#### Rust - Loading TOML with toml crate

```toml
[server]
host = "0.0.0.0"
port = 8080

[server.ssl]
cert = "/path/to/cert.pem"
key = "/path/to/key.pem"
```

_exec_
```bash
cargo run
```

_output_
```bash
Server listening on 0.0.0.0:8080
```

Rust uses the toml crate to parse TOML files.

- Rust has strong typing for TOML values.
- Use serde for deserializing into structs.
- Includes validation through type checking.

#### TOML validation and schema

```toml
# Configuration that should be validated
[app]
name = "Service"

# Required fields: app.name, server.port
# Optional fields: debug, logging.level

[server]
port = 8080
# host must be an IP or hostname
host = "0.0.0.0"

[logging]
level = "info"  # must be: debug, info, warn, error
```

_exec_
```bash
validate-toml --schema config.schema.json config.toml
```

_output_
```bash
Configuration is valid
```

Validation ensures TOML matches expected structure.

- JSON Schema can define TOML structure.
- Type checking during deserialization.
- Document required vs optional fields.

**Best practices:**

- Use language-native libraries when possible.
- Validate TOML structure against a schema.
- Provide default values for optional configuration.
- Handle missing configuration files gracefully.

**Common errors:**

- **Assuming all TOML parsers handle all types**: Check library documentation for type support.
- **Not validating parsed configuration**: Validate required fields and types after loading.

**Advanced notes:**

- **Configuration Merging:** Consider merging multiple TOML files for environment-specific configs.
- **Hot Reloading:** Some applications support reloading config without restart.
