DevToolBoxGRATIS
Blog

Formateador y Validador JSON: Formatea y Valida JSON Online

12 min de lecturapor DevToolBox

Las herramientas de formateador JSON y validador JSON son esenciales para todo desarrollador que trabaje con APIs, archivos de configuracion e intercambio de datos. Ya sea que necesite formatear JSON para legibilidad, validar JSON en linea para detectar errores de sintaxis o embellecer JSON para depuracion, esta guia completa cubre todo. Nuestra herramienta gratuita de formateo JSON en linea maneja formateo, validacion, minificacion y deteccion de errores instantaneamente en su navegador.

Prueba nuestra herramienta gratuita de formateo y validacion JSON.

Que es JSON?

JSON (JavaScript Object Notation) es un formato de intercambio de datos ligero, basado en texto, facil de leer y escribir para humanos, y facil de analizar y generar para maquinas. Se ha convertido en el estandar de facto para el intercambio de datos en APIs web, archivos de configuracion y bases de datos NoSQL.

Un documento JSON consta de dos estructuras: objetos (colecciones de pares clave-valor entre llaves {}) y arrays (listas ordenadas de valores entre corchetes []). Los valores pueden ser cadenas, numeros, booleanos, null, objetos o arrays.

JSON esta definido por RFC 8259 y ECMA-404. El tipo de medio es application/json y la extension de archivo es .json. A diferencia de XML, JSON no soporta comentarios, espacios de nombres ni atributos.

Por que necesitas un formateador JSON

Legibilidad: El JSON crudo de las APIs es a menudo una linea larga sin espacios. Un formateador JSON agrega indentacion y saltos de linea.

Depuracion: Un validador JSON identifica la ubicacion exacta de los errores de sintaxis en segundos.

Validacion: Siempre valide JSON antes de desplegar para evitar fallos silenciosos en produccion.

Minificacion: Minificar JSON elimina espacios innecesarios, reduce el tamano y acelera las respuestas API.

Errores de sintaxis JSON comunes

Un error de sintaxis JSON puede romper toda su aplicacion. Aqui estan los errores mas frecuentes:

Comas finales: JSON no permite comas despues del ultimo elemento. {"a": 1, "b": 2,} es invalido.

// INVALID: trailing comma
{
  "name": "John",
  "age": 30,
}

// VALID: no trailing comma
{
  "name": "John",
  "age": 30
}

Comillas simples: JSON requiere comillas dobles. {'name': 'John'} es invalido.

// INVALID: single quotes
{'name': 'John', 'age': 30}

// VALID: double quotes
{"name": "John", "age": 30}

Claves sin comillas: Cada clave debe ser una cadena entre comillas dobles.

Comentarios: JSON estandar no soporta comentarios. Use JSONC, YAML o TOML.

// INVALID: comments not allowed in JSON
{
  "name": "John", // this is a comment
  "age": 30       /* block comment */
}

// VALID: no comments
{
  "name": "John",
  "age": 30
}

undefined o NaN: JSON solo soporta null, no undefined, NaN o Infinity.

// INVALID in JSON (JavaScript-specific values)
{
  "value1": undefined,
  "value2": NaN,
  "value3": Infinity
}

// VALID: use null instead
{
  "value1": null,
  "value2": null,
  "value3": null
}

Corchetes faltantes: Cada { o [ debe tener su cierre correspondiente.

Secuencias de escape invalidas: JSON soporta secuencias especificas: \", \\, \n, \r, \t, \uXXXX.

Como formatear JSON

Varios metodos para formatear JSON segun su flujo de trabajo:

Formateador JSON en linea: Pegue sus datos en nuestra herramienta gratuita para formateo y validacion instantaneos.

Linea de comandos con jq: jq es el procesador JSON mas potente para la linea de comandos.

Modulo Python integrado: python -m json.tool archivo.json formatea directamente desde el terminal.

Extensiones IDE: VS Code tiene formateo JSON integrado (Shift+Alt+F). JetBrains ofrece Ctrl+Alt+L.

DevTools del navegador: Las DevTools formatean automaticamente las respuestas JSON en la pestana Red.

Reglas de validacion JSON

Para validar correctamente JSON, aqui estan las reglas de RFC 8259:

Tipos de datos: JSON soporta seis tipos: string, number, boolean, null, object y array.

// All six JSON data types demonstrated:
{
  "string": "Hello World",
  "number": 42.5,
  "boolean": true,
  "nullValue": null,
  "object": {
    "nested": "value"
  },
  "array": [1, "two", false, null, {"key": "val"}, [1,2,3]]
}

Cadenas: Deben estar entre comillas dobles con secuencias de escape especificas.

Numeros: Enteros o decimales, notacion cientifica permitida, sin ceros iniciales ni NaN/Infinity.

// Valid JSON numbers:
42          // integer
-17         // negative integer
3.14        // floating point
2.5e10      // scientific notation
-1.23e-4    // negative scientific notation

// INVALID JSON numbers:
01          // leading zero not allowed
.5          // must have digit before decimal
+1          // leading plus not allowed
0xFF        // hex not allowed
0o77        // octal not allowed
NaN         // not a valid JSON value
Infinity    // not a valid JSON value

Objetos: Las claves deben ser cadenas unicas. Objetos vacios {} son validos.

Arrays: Tipos mixtos permitidos. Arrays vacios [] validos. Anidacion arbitraria.

Codificacion: UTF-8 es el estandar y mas utilizado.

Valor de nivel superior: RFC 8259 permite cualquier valor JSON en el nivel superior.

Ejemplos de codigo: formatear y validar JSON

JavaScript: formatear y validar JSON

JavaScript proporciona JSON.parse() y JSON.stringify() para validacion y formateo:

// ===== JSON.parse(): Validate JSON =====

// Valid JSON string
const jsonString = '{"name": "Alice", "age": 30, "active": true}';
const data = JSON.parse(jsonString);
console.log(data.name); // "Alice"

// Validate JSON safely with try/catch
function isValidJSON(str) {
  try {
    JSON.parse(str);
    return true;
  } catch (e) {
    console.error('JSON syntax error:', e.message);
    return false;
  }
}

isValidJSON('{"valid": true}');     // true
isValidJSON('{invalid: true}');     // false — "Unexpected token i"
isValidJSON('{"trailing": 1,}');    // false — "Unexpected token }"

// ===== JSON.stringify(): Format / Pretty Print JSON =====

const obj = {
  name: "Alice",
  age: 30,
  address: {
    city: "New York",
    zip: "10001"
  },
  hobbies: ["reading", "coding", "hiking"]
};

// Pretty print with 2-space indentation
const formatted = JSON.stringify(obj, null, 2);
console.log(formatted);
/*
{
  "name": "Alice",
  "age": 30,
  "address": {
    "city": "New York",
    "zip": "10001"
  },
  "hobbies": [
    "reading",
    "coding",
    "hiking"
  ]
}
*/

// Pretty print with 4-space indentation
console.log(JSON.stringify(obj, null, 4));

// Pretty print with tab indentation
console.log(JSON.stringify(obj, null, "\t"));

// Minify JSON (no whitespace)
const minified = JSON.stringify(obj);
// {"name":"Alice","age":30,"address":{"city":"New York","zip":"10001"},...}

// Custom replacer: filter specific keys
const filtered = JSON.stringify(obj, ["name", "age"], 2);
/*
{
  "name": "Alice",
  "age": 30
}
*/

// Reviver function: transform values during parsing
const parsed = JSON.parse('{"date": "2025-01-15T00:00:00Z"}', (key, value) => {
  if (key === 'date') return new Date(value);
  return value;
});
console.log(parsed.date instanceof Date); // true

Python: formatear y validar JSON

El modulo json de Python proporciona json.dumps() con el parametro indent:

import json

# ===== json.loads(): Validate JSON =====

json_string = '{"name": "Alice", "age": 30, "active": true}'
data = json.loads(json_string)
print(data["name"])  # "Alice"

# Validate JSON safely
def is_valid_json(s):
    try:
        json.loads(s)
        return True
    except json.JSONDecodeError as e:
        print(f"JSON syntax error at line {e.lineno}, col {e.colno}: {e.msg}")
        return False

is_valid_json('{"valid": true}')      # True
is_valid_json('{invalid: true}')      # False
is_valid_json('{"trailing": 1,}')     # False

# ===== json.dumps(): Format / Pretty Print JSON =====

data = {
    "name": "Alice",
    "age": 30,
    "address": {
        "city": "New York",
        "zip": "10001"
    },
    "hobbies": ["reading", "coding", "hiking"]
}

# Pretty print with 2-space indentation
formatted = json.dumps(data, indent=2)
print(formatted)

# Pretty print with sorted keys
formatted_sorted = json.dumps(data, indent=2, sort_keys=True)
print(formatted_sorted)

# Minify JSON (compact output)
minified = json.dumps(data, separators=(",", ":"))
print(minified)
# {"name":"Alice","age":30,"address":{"city":"New York","zip":"10001"},...}

# Handle non-ASCII characters (useful for i18n)
data_intl = {"city": "Tokyo", "greeting": "Hello"}
print(json.dumps(data_intl, ensure_ascii=False, indent=2))

# Read and format a JSON file
with open("data.json", "r") as f:
    data = json.load(f)

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

# Command line: python -m json.tool
# $ echo '{"a":1,"b":2}' | python -m json.tool
# {
#     "a": 1,
#     "b": 2
# }

Linea de comandos: jq, python y node

La linea de comandos ofrece varias herramientas para formatear y validar JSON:

# ===== jq: The Swiss Army knife for JSON =====

# Pretty print JSON
echo '{"name":"Alice","age":30}' | jq .
# {
#   "name": "Alice",
#   "age": 30
# }

# Minify JSON (compact output)
echo '{
  "name": "Alice",
  "age": 30
}' | jq -c .
# {"name":"Alice","age":30}

# Extract specific fields
echo '{"name":"Alice","age":30,"city":"NYC"}' | jq '{name, city}'
# {"name": "Alice", "city": "NYC"}

# Format a JSON file
jq . input.json > formatted.json

# Validate JSON (exit code 0 = valid, non-zero = invalid)
echo '{"valid": true}' | jq . > /dev/null 2>&1 && echo "Valid" || echo "Invalid"
echo '{invalid}' | jq . > /dev/null 2>&1 && echo "Valid" || echo "Invalid"

# Sort keys
echo '{"b":2,"a":1,"c":3}' | jq -S .
# {"a": 1, "b": 2, "c": 3}

# ===== python -m json.tool =====

# Format JSON from stdin
echo '{"a":1,"b":2}' | python3 -m json.tool

# Format a JSON file
python3 -m json.tool input.json output.json

# Sort keys
echo '{"b":2,"a":1}' | python3 -m json.tool --sort-keys

# ===== Node.js one-liner =====

# Pretty print JSON
echo '{"a":1,"b":2}' | node -e "process.stdin.resume();let d='';process.stdin.on('data',c=>d+=c);process.stdin.on('end',()=>console.log(JSON.stringify(JSON.parse(d),null,2)))"

# Simpler: use node -p
node -p "JSON.stringify({a:1,b:[2,3]}, null, 2)"

Pipeline curl + jq

Un flujo de trabajo comun: obtener JSON de una API y formatearlo con curl pipe a jq:

# Fetch and format JSON from a REST API
curl -s https://api.github.com/users/octocat | jq .

# Fetch, extract specific fields, and format
curl -s https://api.github.com/users/octocat | jq '{login, name, bio, public_repos}'

# Fetch and validate (check exit code)
curl -s https://api.example.com/data | jq . > /dev/null 2>&1
if [ $? -eq 0 ]; then
  echo "Response is valid JSON"
else
  echo "Response is NOT valid JSON"
fi

# POST JSON and format the response
curl -s -X POST https://api.example.com/data \
  -H "Content-Type: application/json" \
  -d '{"name":"Alice","age":30}' | jq .

# Save formatted JSON to file
curl -s https://api.github.com/users/octocat | jq . > user.json

# Minify before sending (reduce payload size)
DATA=$(jq -c . large-payload.json)
curl -s -X POST https://api.example.com/data \
  -H "Content-Type: application/json" \
  -d "$DATA" | jq .

Mejores practicas JSON

Siga estas mejores practicas para escribir JSON limpio y eficiente:

camelCase para claves: La mayoria de APIs JSON usan camelCase. Sea consistente.

// camelCase (recommended for most APIs)
{
  "firstName": "Alice",
  "lastName": "Smith",
  "phoneNumber": "+1-555-0123",
  "isActive": true
}

// snake_case (common in Python/Ruby ecosystems)
{
  "first_name": "Alice",
  "last_name": "Smith",
  "phone_number": "+1-555-0123",
  "is_active": true
}

Anidacion superficial: JSON profundamente anidado (mas de 3-4 niveles) es dificil de leer.

// BAD: deeply nested (hard to read and parse)
{
  "company": {
    "departments": {
      "engineering": {
        "teams": {
          "frontend": {
            "members": [{"name": "Alice"}]
          }
        }
      }
    }
  }
}

// BETTER: flattened structure
{
  "companyId": "acme",
  "departmentId": "engineering",
  "teamId": "frontend",
  "members": [{"name": "Alice"}]
}

Archivos grandes: Para archivos JSON de varios MB, use parsers de streaming.

JSON Schema: Valide payloads contra JSON Schema con ajv o jsonschema.

// JSON Schema example for validating user objects
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "name": { "type": "string", "minLength": 1 },
    "age": { "type": "integer", "minimum": 0 },
    "email": { "type": "string", "format": "email" },
    "roles": {
      "type": "array",
      "items": { "type": "string" },
      "minItems": 1
    }
  },
  "required": ["name", "email"]
}

Sin datos binarios: JSON es texto. Use Base64 o URLs para datos binarios.

Manejo consistente de null: Decida si omite o incluye explicitamente las claves null.

JSON vs Alternativas: YAML, TOML, XML

JSON no es el unico formato de serializacion. Aqui una comparacion rapida:

FeatureJSONYAMLTOMLXML
ReadabilityGoodExcellentExcellentModerate
CommentsNoYesYesYes
Data types6 typesRich (dates, etc.)Rich (dates, etc.)Text only
NestingUnlimitedUnlimitedLimitedUnlimited
Multi-line stringsNoYesYesYes (CDATA)
Parser supportUniversalWideGrowingUniversal
File sizeSmallSmallerSmallestLarge (verbose)
Best forAPIs, dataConfig filesSimple configDocuments, SOAP

Elija JSON para APIs, YAML para archivos de configuracion editables, TOML para configuraciones simples, XML para estandares existentes (SOAP, RSS).

Preguntas frecuentes

Como formateo JSON en linea?

Pegue su JSON crudo en una herramienta de formateo como la nuestra. La herramienta valida automaticamente la sintaxis, agrega indentacion y resalta errores. Puede elegir entre 2 o 4 espacios. La herramienta funciona completamente en su navegador.

Cuales son los errores de sintaxis JSON comunes?

Los mas comunes son: comas finales, comillas simples en vez de dobles, claves sin comillas, comentarios, valores undefined/NaN, corchetes faltantes y secuencias de escape invalidas.

Cual es la diferencia entre JSON y YAML?

JSON usa llaves y comillas dobles, YAML usa indentacion. YAML soporta comentarios y cadenas multilinea. JSON es mejor para intercambio maquina-a-maquina, YAML para configuracion. JSON es un subconjunto estricto de YAML.

Dominar el formateo y la validacion JSON es esencial para desarrolladores modernos. Use nuestra herramienta gratuita para formateo y validacion instantaneos.

Formatee, valide y minifique JSON instantaneamente con nuestra herramienta gratuita.

𝕏 Twitterin LinkedIn
¿Fue útil?

Mantente actualizado

Recibe consejos de desarrollo y nuevas herramientas.

Sin spam. Cancela cuando quieras.

Prueba estas herramientas relacionadas

{ }JSON FormatterTSJSON to TypeScriptGoJSON to Go StructJSON Validator

Artículos relacionados

JSON vs YAML vs TOML: ¿Qué formato de configuración usar?

Compara los formatos de configuración JSON, YAML y TOML.

Validación JSON Schema: Tipos, herramientas y mejores prácticas

Todo sobre la validación JSON Schema: desde tipos básicos hasta patrones avanzados, bibliotecas de validación e integración con TypeScript y APIs.

JSON Parse Error: Unexpected Token — Cómo encontrarlo y solucionarlo

Soluciona errores de parsing JSON paso a paso. Causas, localización y herramientas de validación.

Formateador JSON: Guia completa para formatear y embellecer JSON (2026)

Aprende a formatear JSON en linea, en VS Code, en la linea de comandos y en JavaScript/Python. Validacion, minificacion, visor y errores comunes.