TOML to JSON Converter

Convert TOML configuration files (Cargo.toml, pyproject.toml) into cleanly formatted JSON structures.

4.9 / 5· 148 verified ratings
•
100% Client-Side Privacy
•
Verified 2026 Engine
Loading tool engine...
Frequently Used With:JSON Formatter & Validator →JSON Diff & Comparison Tool →XML to JSON Converter →YAML to JSON Converter →
Institutional-Grade Accuracy & Client-Side Privacy Guarantee

Unlike conventional calculator sites that send your financial numbers, payload data, or code snippets across remote web servers, Affi-Chain processes all mathematical derivations, algorithms, and data parsing 100% locally within your browser sandbox. No tracking cookies, no server-side retention, and zero transmission lag.

Architectural & Semantic Foundations of TOML vs. JSON

TOML (Tom's Obvious Minimal Language), created by GitHub co-founder Tom Preston-Werner, is an explicit, strongly typed configuration file format engineered for human authoring and unambiguous parsing. Unlike formats that rely on significant whitespace indentation (such as YAML) or syntactically verbose punctuation (such as JSON with mandatory braces and quotes around every key), TOML maps directly to a hash table dictionary using intuitive declarative section headers.

+---------------------------------------------------------------------------------------------------+
|                                  TOML TO JSON DATA TRANSLATION PIPELINE                            |
+---------------------------------------------------------------------------------------------------+
|  DECLARATIVE TOML SYNTAX                     LEXER / PARSER ENGINE            CANONICAL RFC 8259  |
|  [database.primary]                          - Table Hierarchy Traversal      {                   |
|  host = "10.0.0.1"                    -->    - Dotted Key Unflattening  -->     "database": {     |
|  ports = [ 5432, 5433 ]                      - Native Datetime Parsing            "primary": {    |
|  [[database.replicas]]                       - Type Normalization                   "host": ...   |
|  host = "10.0.0.2"                           - Array of Tables Resolution       }                 |
+---------------------------------------------------------------------------------------------------+

The Configuration Divergence: Human Authoring vs. Machine Interchange

While TOML has emerged as the definitive standard for modern package management and build configurations (including Rust's Cargo.toml, Python's pyproject.toml per PEP 518/621, and Hugo's config.toml), JSON (JavaScript Object Notation, RFC 8259) remains the ubiquitous lingua franca for REST APIs, cloud microservice payloads, web dashboards, and distributed databases.

Converting TOML to JSON enables:

  1. Automated CI/CD Processing: Extracting semantic versions, build flags, or deployment environments within GitHub Actions or GitLab CI using standard JSON query tools like jq.
  2. Schema Validation: Validating user-authored configurations against formal JSON Schema (draft-07 / 2020-12) definitions.
  3. Dynamic Frontend Hydration: Loading backend application configurations directly into React, Vue, or Next.js web application state without requiring heavy client-side TOML parsers.

Type Mapping & Syntax Grammar Matrix

TOML v1.0.0 defines explicit lexical data types that map to the narrower JSON type system (String, Number, Object, Array, Boolean, Null):

+---------------------------------------------------------------------------------------------------+
|                                      TYPE CONVERSION TAXONOMY                                     |
+---------------------------------------------------------------------------------------------------+
|  TOML Type                      TOML Syntax Representation            JSON Target Representation  |
|  -----------------------------  ------------------------------------  --------------------------  |
|  Table                          [server.web]                          "server": { "web": { ... } }|
|  Array of Tables                [[plugins]]                           "plugins": [ { ... } ]      |
|  Inline Table                   conn = { port = 8080, tls = true }    "conn": {"port": 8080, ...} |
|  Offset Date-Time (RFC 3339)    2026-11-18T22:30:00Z                  "2026-11-18T22:30:00Z" (str)|
|  Local Date                     2026-11-18                            "2026-11-18" (string)       |
|  Integer (Hex / Oct / Bin)      0xDEAD, 0o755, 0b1101                 57005, 493, 13 (Number)     |
|  Float (Special Values)         inf, -inf, nan                        null or String (RFC rule)   |
|  Literal String                 '''C:\Users\path\test'''              "C:\\Users\\path\\test"     |
|  Multiline Basic String         """First line\nSecond line"""         "First line\nSecond line"   |
+---------------------------------------------------------------------------------------------------+

Lexical Mechanics: Tables vs. Arrays of Tables

  1. Standard Tables ([table]): Define key-value dictionaries. Nested tables can be declared with dot notation ([servers.alpha]) or inline (servers = { alpha = { ... } }).
  2. Array of Tables ([[products]]): Repeated occurrences of a double-bracketed header create a sequential array of dictionary objects in JSON. Each subsequent [[products]] appends a new JSON object to the products array.
  3. Dotted Key Syntactic Sugar: In TOML, site.title = "Docs" creates { "site": { "title": "Docs" } } automatically, avoiding redundant nested table declarations.

Production Code Implementation

Python: Robust TOML to JSON Transpiler with Datetime and Special Float Handling

Python 3.11 introduced tomllib directly into the standard library. The script below implements robust conversion with ISO 8601 stringification for date objects and sanitization for non-compliant IEEE floats.

#!/usr/bin/env python3
"""
Production TOML to JSON Converter supporting TOML v1.0.0,
handling RFC 3339 Datetimes, Decimal normalization, and Special Floats.
"""

import sys
import json
import math
from datetime import datetime, date, time
from typing import Any

# Use standard library tomllib (Python 3.11+) or tomli fallback
if sys.version_info >= (3, 11):
    import tomllib
else:
    import tomli as tomllib


class TOMLJSONEncoder(json.JSONEncoder):
    """
    Custom JSON Encoder that translates native TOML datetimes
    and handles non-compliant float primitives (NaN, Infinity).
    """
    def default(self, obj: Any) -> Any:
        if isinstance(obj, (datetime, date, time)):
            return obj.isoformat()
        return super().default(obj)


def sanitize_toml_values(data: Any) -> Any:
    """
    Recursively inspects data to handle RFC 8259 JSON compliance:
    Converts float('nan'), float('inf'), and float('-inf') to null or string.
    """
    if isinstance(data, dict):
        return {k: sanitize_toml_values(v) for k, v in data.items()}
    elif isinstance(data, list):
        return [sanitize_toml_values(item) for item in data]
    elif isinstance(data, float):
        if math.isnan(data):
            return None  # Or "NaN" based on schema requirements
        elif math.isinf(data):
            return "Infinity" if data > 0 else "-Infinity"
        return data
    return data


def convert_toml_to_json(toml_string: str, indent: int = 2) -> str:
    """
    Parses a raw TOML string and outputs an indented, RFC 8259-compliant JSON string.
    """
    try:
        parsed_dict = tomllib.loads(toml_string)
    except tomllib.TOMLDecodeError as err:
        raise ValueError(f"Invalid TOML Syntax: {err}") from err

    sanitized = sanitize_toml_values(parsed_dict)
    return json.dumps(sanitized, cls=TOMLJSONEncoder, indent=indent)


# Demonstration
if __name__ == "__main__":
    sample_toml = """
    # Enterprise Infrastructure Configuration
    title = "Affichain Microservices Cluster"
    release_date = 2026-11-18T22:30:00Z
    debug_mode = false

    [server.network]
    bind_ip = "0.0.0.0"
    ports = [ 80, 443, 8080 ]
    max_connections = 50_000

    [[databases]]
    role = "primary"
    engine = "PostgreSQL"
    port = 5432
    options = { pool_size = 20, ssl = true }

    [[databases]]
    role = "replica"
    engine = "PostgreSQL"
    port = 5433
    options = { pool_size = 50, ssl = true }
    """

    json_output = convert_toml_to_json(sample_toml)
    print("--- CONVERTED JSON OUTPUT ---")
    print(json_output)

TypeScript: Microservice Transpiler using smol-toml

/**
 * Zero-dependency TypeScript TOML to JSON Transpiler
 * utilizing 'smol-toml' for strict TOML v1.0.0 compliance.
 */

import { parse } from "smol-toml";

export interface TranspileOptions {
  prettyPrint?: boolean;
  indentSpaces?: number;
  handleDateAsISO?: boolean;
}

export function transpileTomlToJson(
  tomlContent: string,
  options: TranspileOptions = {}
): string {
  const { prettyPrint = true, indentSpaces = 2, handleDateAsISO = true } = options;

  let parsedObject: Record<string, unknown>;
  try {
    parsedObject = parse(tomlContent) as Record<string, unknown>;
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`TOML Parsing Failure: ${message}`);
  }

  const replacer = (key: string, value: unknown) => {
    if (handleDateAsISO && value instanceof Date) {
      return value.toISOString();
    }
    // Handle special float numbers that crash strict JSON parsers
    if (typeof value === "number") {
      if (Number.isNaN(value)) return null;
      if (!Number.isFinite(value)) return value > 0 ? "Infinity" : "-Infinity";
    }
    return value;
  };

  return JSON.stringify(
    parsedObject,
    replacer,
    prettyPrint ? indentSpaces : undefined
  );
}

Configuration Serialization Formats Comparison Matrix

SpecificationPrimary StrengthWhitespace Sensitive?Native Datetime SupportComments Supported?Schema Validation EcosystemParsing Overhead
TOML (v1.0.0)Human authoring, unambiguous key hierarchyNo (Brackets & delimiters)Yes (RFC 3339 built-in)Yes (# hash comments)Growing (Taplo, JSON Schema)Moderate
JSON (RFC 8259)Universal machine interchange, zero ambiguityNoNo (String representation)No (Strict specification)Comprehensive (JSON Schema)Ultra Low (C-level native)
YAML (v1.2)Concise human readability, document streamingYes (Indentation-critical)Yes (Implicit timestamp)Yes (# hash comments)Extensive (JSON Schema / Kube)High (Complex state machine)
INI FormatSimple legacy flat sectionsNoNo (Unstandardized strings)Yes (; or #)Virtually NoneVery Low
HCL (HashiCorp)Infrastructure-as-code with expressionsNoNoYes (# and //)Specialized (HCL Schemas)Moderate

Critical Edge Cases & Common Conversion Traps

1. The TOML Date and Time Fidelity Problem

TOML supports four distinct temporal types:

  • Offset Date-Time: 1979-05-27T07:32:00Z (complete UTC timestamp with timezone offset).
  • Local Date-Time: 1979-05-27T07:32:00 (timestamp lacking timezone context).
  • Local Date: 1979-05-27 (calendar date without time).
  • Local Time: 07:32:00 (wall clock time without date).

Standard RFC 8259 JSON has no temporal type; all dates must be coerced into strings. When serializing back to JSON, systems must avoid naive UTC conversions on Local Dates or Local Times, as converting 07:32:00 into 1970-01-01T07:32:00.000Z introduces incorrect timezone assumptions.

2. Heterogeneous Array Evolution (TOML 0.4 vs. 1.0)

In legacy TOML v0.4, arrays were strictly homogeneous: mixed = [1, "two", 3.0] was illegal syntax that threw parse exceptions. In modern TOML v1.0.0, heterogeneous arrays are fully permitted. However, when converting to typed JSON systems or database tables, downstream consumers that expect uniform arrays may fail.

3. Special Floating-Point Values (nan, inf, -inf)

TOML explicitly supports IEEE 754 special values:

error_margin = nan
max_threshold = inf
min_threshold = -inf

Strict JSON (RFC 8259) prohibits NaN, Infinity, and -Infinity. If a standard JSON serializer attempts to serialize these numbers, it will either throw a ValueError (Python), serialize them as null (JavaScript JSON.stringify), or produce non-standard JSON ("error_margin": NaN) that crashes strict downstream parsers. Transpilers must configure an explicit sanitization strategy.

4. Dotted Key Collision and Key Overwriting

In TOML, keys cannot be redefined once initialized:

[fruit]
apple.color = "red"
# Illegal error: attempted to redefine table 'fruit.apple' as a string
# fruit.apple = "gala"

When parsing malformed or poorly authored TOML, transpilers must verify that scalar key assignments do not collide with existing table namespaces.

5. Multi-line String Trimming and Escaping

TOML differentiates between:

  • Literal Strings ('''...'''): Raw strings where backslashes are preserved verbatim without escape parsing (ideal for regular expressions and Windows directory paths like '''C:\Windows\System32''').
  • Basic Strings ("""..."""): Support full C-style escape sequences (\n, \t, \u00A0). Ending a line with an unescaped backslash \ trims the following newline and all leading whitespace on the next line.

When converting to JSON, literal backslashes must be properly escaped ("C:\\Windows\\System32"), otherwise invalid escape sequence errors will corrupt the generated JSON document.

Frequently Asked Questions

What is TOML primarily used for?
TOML (Tom's Obvious Minimal Language) is designed as an unambiguous, human-readable configuration file format widely used in Rust (Cargo) and Python (Poetry/pyproject.toml).

Explore Related Utilities