🛠️ToolsShed

Conversor TOML ↔ JSON

Converta entre os formatos TOML e JSON e valide a sintaxe TOML.

Perguntas Frequentes

Implementação de Código

# Python 3.11+ has tomllib built-in (read-only)
# For older versions: pip install tomli
# For writing: pip install tomli-w

import tomllib  # Python 3.11+
# import tomli as tomllib  # Python < 3.11

toml_text = """
[package]
name = "my-app"
version = "1.0.0"
authors = ["Alice <alice@example.com>"]

[dependencies]
requests = ">=2.28.0"
flask = { version = ">=3.0", optional = true }

[[server]]
host = "web1.example.com"
port = 8080

[[server]]
host = "web2.example.com"
port = 8081
"""

# Parse TOML string
data = tomllib.loads(toml_text)
print(data["package"]["name"])      # my-app
print(data["dependencies"])          # {'requests': '>=2.28.0', ...}
print(data["server"])                # [{'host': 'web1...', 'port': 8080}, ...]

# Parse from file
with open("pyproject.toml", "rb") as f:  # Must open in binary mode!
    config = tomllib.load(f)

# Writing TOML (requires tomli-w or tomllib doesn't support write)
# pip install tomli-w
import tomli_w
output = tomli_w.dumps({"key": "value", "count": 42})
print(output)
# key = "value"
# count = 42

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.