How to Convert JSON to TOML and Vice Versa

When working with configuration files and data interchange, developers often face a choice: TOML or JSON. Both formats serve important purposes, but they excel in different scenarios. This guide breaks down the differences, shows practical examples, and helps you decide which format to use for your next project.

Understanding TOML and JSON

What is JSON?

JSON (JavaScript Object Notation) is the universal language of the web. It's used everywhere: APIs, databases, configuration files, and data exchange between systems. JSON's strength lies in its simplicity and universal support across all programming languages.

Example JSON:

{
  "name": "John Doe",
  "age": 30,
  "skills": [
    "Python",
    "JavaScript",
    "DevOps"
  ],
  "address": {
    "street": "123 Main St",
    "city": "Springfield",
    "zip_code": 12345
  }
}

What is TOML?

TOML (Tom's Obvious, Minimal Language) is a configuration format designed specifically for humans to write and read easily. It's the standard configuration format for Rust (Cargo), Hugo, Terraform, and many modern tools. TOML reads almost like plain English.

Example TOML:

name: John Doe
age: 30
skills[3]: Python,JavaScript,DevOps
address:
  street: 123 Main St
  city: Springfield
  zip_code: 12345

Both formats represent the same data, but notice the difference in readability.

Why Choose TOML for Configuration?

1. Human-Readable Syntax

TOML eliminates unnecessary punctuation. You don't need quotes around keys or braces around every section. This makes configuration files feel natural to write.

TOML (clean):

server_name = "My App"
debug_mode = true
max_connections = 100

JSON (verbose):

{
  "server_name": "My App",
  "debug_mode": true,
  "max_connections": 100
}

2. Built-In Comments

TOML supports comments, which are essential for explaining configuration options. JSON has no comment support.

# Database configuration
[database]
host = "localhost"          # Server address
port = 5432                 # PostgreSQL port
retry_attempts = 3          # Number of retries on failure

3. Less Error-Prone

TOML's syntax is strict but forgiving. You can't forget a quote or misalign indentation the way you can in YAML. JSON requires perfect punctuation, one missing comma breaks everything.

4. Append-Friendly

TOML is designed so tools can modify configuration files without completely reformatting them. This is important for automated configuration management.

Why Choose JSON?

1. Universal Compatibility

JSON is supported everywhere. Every programming language, every API, every system understands JSON. If you need maximum compatibility, JSON is the answer.

2. Better for APIs and Data Exchange

When systems communicate, they use JSON. It's the standard for REST APIs, webhooks, and microservices. JSON's structure explicitly shows data types, which is crucial for machine-to-machine communication.

3. Simpler Parsing

JSON parsers are highly optimized. For automated systems processing thousands of API calls, JSON's performance is unmatched.

4. Structured Data Interchange

If you're storing records in a database or transferring objects between systems, JSON is the industry standard. It handles complex nested structures naturally.

Real-World Examples

Configuration File: TOML Wins

If you're building a web application, your config file should be TOML:

# app.toml
[app]
name = "My Analytics Tool"
version = "1.0.0"
debug = false

[database]
url = "postgresql://localhost/mydb"
max_pool_size = 20
connection_timeout = 30

[api]
base_url = "https://api.example.com"
timeout = 60

# Logging levels: debug, info, warn, error
[logging]
level = "info"
output = "stdout"

This is infinitely more readable than the equivalent JSON configuration.

API Response: JSON Wins

When an API returns user data, JSON is perfect:

{
  "success": true,
  "data": {
    "users": [
      {
        "id": 1,
        "name": "Alice",
        "email": "[email protected]",
        "roles": [
          "admin",
          "user"
        ],
        "created_at": "2025-01-15T10:30:00Z"
      },
      {
        "id": 2,
        "name": "Bob",
        "email": "[email protected]",
        "roles": [
          "user"
        ],
        "created_at": "2025-01-14T15:22:00Z"
      }
    ]
  }
}

The structure is unambiguous, and every programming language can parse it instantly.

Converting Between TOML and JSON

Sometimes you need to convert between formats. Here's what typically happens:

TOML Input:

[settings]
theme = "dark"
language = "en"
notifications = true

[[database]]
name = "primary"
host = "db1.example.com"

[[database]]
name = "replica"
host = "db2.example.com"

Converted to JSON:

{
  "settings": {
    "theme": "dark",
    "language": "en",
    "notifications": true
  },
  "database": [
    {
      "name": "primary",
      "host": "db1.example.com"
    },
    {
      "name": "replica",
      "host": "db2.example.com"
    }
  ]
}

The data remains identical, only the format changes. You can play with it yourself using our TOML to JSON converter.

Common Use Cases

Use TOML When:

  • Writing configuration files for applications
  • Building Rust projects (Cargo.toml)
  • Creating infrastructure-as-code files (Terraform, Hugo)
  • Managing environment-specific settings
  • Developers need to edit config files directly
  • You want configurations with comments and explanations

Use JSON When:

  • Building REST APIs
  • Exchanging data between systems
  • Storing records in databases
  • Creating webhooks and integrations
  • Working with legacy systems
  • Configuration is generated automatically

Converting TOML to JSON (And Vice Versa)

If you need to convert between formats, you have several options:

Programmatic Conversion

Most languages have libraries for both formats:

Python:

import toml
import json

# Read TOML, convert to JSON
with open('config.toml', 'r') as f:
  data = toml.load(f)

with open('config.json', 'w') as f:
  json.dump(data, f, indent=2)

JavaScript/Node.js:

const toml = require('toml');
const fs = require('fs');

const tomlData = fs.readFileSync('config.toml', 'utf-8');
const data = toml.parse(tomlData);
const json = JSON.stringify(data, null, 2);

fs.writeFileSync('config.json', json);

Online Conversion Tools

For quick conversions without writing code, online converter tools are convenient. They instantly transform TOML to JSON and back, which is helpful during development.

Try our tools:

TOML to JSON Converter Tool

If you frequently convert between TOML and JSON, a dedicated converter tool can save time. These tools typically offer:

  • Real-time conversion - See results as you type
  • Error detection - Instant feedback on syntax errors
  • Bidirectional conversion - Convert both directions seamlessly
  • Copy to clipboard - One-click copying of results
  • Format validation - Ensure your data is valid

Rather than installing libraries or writing scripts for one-off conversions, an online converter is fast, free, and requires no setup. You can play with it yourself here.

When to Convert Between Formats

You might need to convert between TOML and JSON in these scenarios:

1. API Integration

Your application reads TOML configuration files but needs to send data to a JSON API. Convert before making the API call.

2. Legacy System Migration

Moving configuration from a legacy system that uses JSON to a modern tool that expects TOML.

3. Data Export

Exporting configuration from a tool that uses TOML into a system that requires JSON.

4. Cross-Team Workflows

Different teams might use different tools. One team manages TOML configs; another system needs the data as JSON.

Best Practices

Configuration File Best Practices

  • Use TOML for application configuration
  • Include comments explaining what each setting does
  • Group related settings in sections
  • Use descriptive key names
  • Never hardcode secrets (use environment variables instead)

API Data Best Practices

  • Use JSON for API responses and requests
  • Provide clear schema documentation
  • Use consistent naming conventions
  • Include timestamp in ISO 8601 format
  • Return errors in a standardized format

Conclusion

TOML and JSON aren't competing formats, they're designed for different purposes. Use TOML for human-authored configuration files where readability and comment support matter. Use JSON for APIs and system-to-system communication where universal compatibility is critical.

For most modern projects, the answer is simple: use both. Keep your configuration in TOML for clarity and maintainability. Use JSON for data interchange with external systems and APIs.

If you frequently need to convert between these formats during development, an online TOML to JSON converter can streamline your workflow. It's one less tool to configure and one more thing you can do without leaving your browser.

Start using TOML for your next configuration file, your future self will thank you for the improved readability.

Get back to blog