JSON, YAML y TOML son los tres formatos de configuración más populares en desarrollo de software. Cada uno tiene fortalezas y compromisos distintos. Esta guía ofrece una comparación completa para ayudarte a elegir el formato adecuado.
Convierte entre JSON y YAML instantáneamente →
Descripción de cada formato
JSON (JavaScript Object Notation)
JSON fue introducido a principios de los 2000 por Douglas Crockford. Es el estándar de facto para APIs web, archivos como package.json y el intercambio de datos.
YAML (YAML Ain't Markup Language)
YAML fue propuesto en 2001, diseñado para la legibilidad humana. Se usa en Docker Compose, Kubernetes, Ansible y pipelines CI/CD.
TOML (Tom's Obvious Minimal Language)
TOML fue creado en 2013 por Tom Preston-Werner como formato mínimo y sin ambigüedad. Es el estándar para Rust (Cargo.toml), Python (pyproject.toml) y Hugo.
Comparación de sintaxis
Aquí está la misma configuración en los tres formatos:
JSON
{
"server": {
"host": "localhost",
"port": 8080,
"debug": true
},
"database": {
"host": "db.example.com",
"port": 5432,
"name": "myapp",
"credentials": {
"username": "admin",
"password": "secret"
}
},
"features": ["auth", "logging", "cache"],
"max_connections": 100
}YAML
# Server configuration
server:
host: localhost
port: 8080
debug: true
# Database settings
database:
host: db.example.com
port: 5432
name: myapp
credentials:
username: admin
password: secret
features:
- auth
- logging
- cache
max_connections: 100TOML
# Server configuration
max_connections = 100
features = ["auth", "logging", "cache"]
[server]
host = "localhost"
port = 8080
debug = true
[database]
host = "db.example.com"
port = 5432
name = "myapp"
[database.credentials]
username = "admin"
password = "secret"Comparación de características
| Característica | JSON | YAML | TOML |
|---|---|---|---|
| Comentarios | No | Sí (#) | Sí (#) |
| Tipos de datos | string, number, boolean, null, array, object | string, int, float, bool, null, date, array, map + tags | string, integer, float, boolean, datetime, array, table |
| Legibilidad | Medio — llaves y comillas añaden ruido visual | Alto — sintaxis limpia basada en indentación | Alto — estilo INI, secciones explícitas |
| Rigurosidad | Muy estricto — sin comas finales ni comentarios | Flexible — tipado implícito causa sorpresas | Estricto — tipos explícitos, ambigüedad mínima |
| Soporte de herramientas | Excelente — soporte universal | Bueno — parsers en todos los lenguajes principales | Bueno — creciendo, fuerte en Rust/Python/Go |
| Cadenas multi-línea | No (usar \n) | Sí (| literal, > plegado) | Sí (comillas triples) |
Cuándo usar cada formato
Usa JSON cuando...
- Construyes o consumes APIs REST
- Trabajas con package.json o tsconfig.json
- Almacenas datos leídos más por máquinas que por humanos
- Necesitas el soporte de herramientas más amplio
- Intercambio de datos entre lenguajes diferentes
// Typical JSON use cases
// package.json
{
"name": "my-app",
"version": "1.0.0",
"scripts": {
"dev": "next dev",
"build": "next build"
}
}
// tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"strict": true
}
}Usa YAML cuando...
- Escribes archivos Docker Compose o Kubernetes
- Configuras pipelines CI/CD
- Usas Ansible o Helm
- Necesitas comentarios en la configuración
- La legibilidad humana es la prioridad
# Docker Compose
services:
web:
image: nginx:alpine
ports:
- "80:80"
volumes:
- ./html:/usr/share/nginx/html
# GitHub Actions
name: CI
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npm testUsa TOML cuando...
- Configuras proyectos Rust (Cargo.toml)
- Configuras proyectos Python (pyproject.toml)
- Usas Hugo
- Quieres un formato sin coerción de tipos implícita
- Tu config tiene secciones claras
# Cargo.toml (Rust)
[package]
name = "my-app"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1", features = ["full"] }
# pyproject.toml (Python)
[project]
name = "my-package"
version = "1.0.0"
requires-python = ">=3.9"
[tool.ruff]
line-length = 88
target-version = "py39"Trampas comunes
YAML: Problemas de indentación
YAML usa indentación para definir estructura. Mezclar tabs y espacios causa errores frecuentes.
# BAD: mixing tabs and spaces (invisible but breaks YAML)
services:
web: # tab character - YAML error!
image: nginx
# BAD: inconsistent indentation
services:
web:
image: nginx # 4 spaces here
ports: # 2 spaces here - error!
- "80:80"
# GOOD: consistent 2-space indentation
services:
web:
image: nginx
ports:
- "80:80"YAML: El "problema de Noruega"
En YAML 1.1, valores como NO, yes, on, off sin comillas se interpretan como booleanos. El código "NO" (Noruega) se convierte en false.
# The "Norway Problem" - YAML 1.1
countries:
- name: Norway
code: NO # Parsed as boolean false!
- name: Sweden
code: SE # Parsed as string "SE"
- name: Finland
code: FI # Parsed as string "FI"
# Other surprising boolean values in YAML 1.1:
truthy: yes # boolean true
falsy: no # boolean false
enabled: on # boolean true
disabled: off # boolean false
positive: TRUE # boolean true
negative: False # boolean false
# FIX: Always quote values that could be misinterpreted
countries:
- name: Norway
code: "NO" # Now correctly a string
- name: Sweden
code: "SE"
settings:
enabled: "yes" # Now correctly a stringJSON: Comas finales
JSON no permite comas finales. Añadir una coma después del último elemento causa un error de parseo.
// BAD: trailing comma after last element
{
"name": "my-app",
"version": "1.0.0",
"private": true, // <-- trailing comma = PARSE ERROR
}
// BAD: trailing comma in array
{
"colors": [
"red",
"green",
"blue", // <-- trailing comma = PARSE ERROR
]
}
// GOOD: no trailing commas
{
"name": "my-app",
"version": "1.0.0",
"private": true
}TOML: Sintaxis de tablas anidadas
Las estructuras profundamente anidadas en TOML pueden ser verbosas. Cada nivel necesita su propio encabezado [section.subsection].
# TOML: deeply nested config can be verbose
[server]
host = "localhost"
[server.ssl]
enabled = true
[server.ssl.certificates]
cert = "/path/to/cert.pem"
key = "/path/to/key.pem"
[server.ssl.certificates.ca]
bundle = "/path/to/ca-bundle.pem"
# The same in YAML is more compact:
# server:
# host: localhost
# ssl:
# enabled: true
# certificates:
# cert: /path/to/cert.pem
# key: /path/to/key.pem
# ca:
# bundle: /path/to/ca-bundle.pem
# TOML inline tables can help for shallow nesting:
[server]
host = "localhost"
ssl = { enabled = true, cert = "/path/to/cert.pem" }Herramientas de conversión
¿Necesitas cambiar entre formatos? Usa nuestros conversores gratuitos:
Conversor JSON ↔ YAML — conversión bidireccional
Conversor TOML ↔ YAML — conversión instantánea
Preguntas frecuentes
¿Cuál formato se parsea más rápido?
JSON generalmente se parsea más rápido por su gramática simple y estricta. TOML también es rápido. YAML es el más lento por su especificación compleja.
¿Se pueden usar comentarios en JSON?
El JSON estándar (RFC 8259) no soporta comentarios. JSON5 y JSONC extienden JSON con comentarios, pero no son estándar.
¿Por qué YAML trata "NO" como false?
En YAML 1.1, yes/no, on/off y true/false se reconocen como booleanos. El código "NO" (Noruega) se interpreta como false. Siempre pon comillas a estos valores.
¿Es TOML mejor que YAML para configuración?
TOML suele preferirse para configs simples y planas. YAML maneja mejor las estructuras profundamente anidadas. Depende del ecosistema.
¿Se pierden datos al convertir entre formatos?
Para estructuras comunes la conversión es sin pérdida. Características específicas (anclas YAML, comentarios) se pierden al convertir a JSON.
Convierte entre JSON y YAML instantáneamente →
Convierte entre TOML y YAML con nuestra herramienta gratuita →