← Volver al Blog

Guía Completa de JSON Beautifier: Formatear y Embellecer JSON

Aprende a formatear y embellecer JSON con herramientas online, línea de comandos y programáticamente. Guía completa de JSON beautification.

Big JSON Team11 min de lecturaHerramientas
B

Big JSON Team

Technical Writer

Expert in JSON data manipulation, API development, and web technologies. Passionate about creating tools that make developers' lives easier.

11 min lectura

# Guía Completa de JSON Beautifier: Formatear y Embellecer JSON

JSON beautification (o embellecimiento) transforma JSON compacto y difícil de leer en un formato elegante y estructurado. Esta guía completa te enseñará todas las formas de beautificar JSON.

¿Qué es JSON Beautification?

JSON beautification es el proceso de formatear JSON para hacerlo legible para humanos mediante:

  • ✅ Indentación apropiada
  • ✅ Saltos de línea
  • ✅ Espaciado consistente
  • ✅ Resaltado de sintaxis
  • ✅ Ordenamiento de claves

Antes (Minificado)

{"nombre":"Ana García","edad":28,"ciudad":"Madrid","habilidades":["JavaScript","Python","React"],"activo":true,"contacto":{"email":"ana@ejemplo.com","telefono":"+34600123456"}}

Después (Beautificado)

{

"nombre": "Ana García",

"edad": 28,

"ciudad": "Madrid",

"habilidades": [

"JavaScript",

"Python",

"React"

],

"activo": true,

"contacto": {

"email": "ana@ejemplo.com",

"telefono": "+34600123456"

}

}

Herramientas Online de Beautification

Big JSON Viewer (Recomendado)

URL: bigjson.online Características:
✓ Beautification automática

✓ Maneja archivos enormes (GB+)

✓ Vista de árbol interactiva

✓ Resaltado de sintaxis

✓ Búsqueda y filtrado

✓ Procesamiento local (privado)

✓ Exportar formateado

✓ Sin límites de tamaño

Cómo usar:
1. Visita bigjson.online
  • Pega JSON o carga archivo
  • Automáticamente beautificado
  • Explora con vista de árbol
  • Copia o descarga resultado
  • Ideal para:
    • Archivos JSON grandes
    • Datos complejos anidados
    • Análisis y depuración
    • Compartir con equipo

    JSONLint

    URL: jsonlint.com Uso:
    1. Pega JSON minificado
    
  • Click "Validate JSON"
  • Ver JSON beautificado
  • Corregir errores si los hay
  • Ventajas:
    • Simple y rápido
    • Validación incluida
    • Mensajes de error claros

    JSON Formatter

    URL: jsonformatter.org Características:
    ✓ Beautify y minify
    

    ✓ Validación

    ✓ Vista de árbol

    ✓ Compartir por URL

    ✓ Descarga directa

    JSON Editor Online

    URL: jsoneditoronline.org Características:
    ✓ Vista dual (árbol y código)
    

    ✓ Edición visual

    ✓ Beautification automática

    ✓ Ordenar claves

    ✓ Búsqueda y reemplazo

    Beautify en Editores de Código

    Visual Studio Code

    Método 1: Atajo de teclado
    Windows/Linux: Shift + Alt + F
    

    macOS: Shift + Option + F

    Método 2: Command Palette
    1. Ctrl+Shift+P (Cmd+Shift+P en Mac)
    
  • Buscar "Format Document"
  • Enter
  • Configuración automática:
    {
    

    "editor.formatOnSave": true,

    "editor.formatOnPaste": true,

    "[json]": {

    "editor.defaultFormatter": "vscode.json-language-features",

    "editor.tabSize": 2,

    "editor.insertSpaces": true

    }

    }

    Extensión Prettier:
    1. Instalar extensión "Prettier - Code formatter"
    
  • Configurar como formatter por defecto
  • Formateo automático al guardar
  • Configuración de Prettier:

    {
    

    "prettier.tabWidth": 2,

    "prettier.useTabs": false,

    "prettier.singleQuote": false,

    "prettier.trailingComma": "none"

    }

    Sublime Text

    Con Plugin Pretty JSON:
    1. Ctrl+Shift+P → Package Control: Install Package
    
  • Buscar "Pretty JSON"
  • Instalar
  • Uso: Ctrl+Alt+J (Windows/Linux) / Cmd+Ctrl+J (Mac)
  • Configuración:
    {
    

    "indent": 2,

    "sort_keys": false,

    "ensure_ascii": false

    }

    Atom

    Con beautify package:
    apm install atom-beautify
    Uso:
    Ctrl+Alt+B (Windows/Linux)
    

    Cmd+Alt+B (Mac)

    IntelliJ IDEA / WebStorm

    Atajo:
    Windows/Linux: Ctrl + Alt + L
    

    macOS: Cmd + Option + L

    Configuración:
    Settings → Editor → Code Style → JSON
    
    • Tab size: 2
    • Indent: 2
    • Continuation indent: 4

    Beautify en Línea de Comandos

    Con jq

    Instalación:
    # macOS
    

    brew install jq

    # Ubuntu/Debian

    sudo apt-get install jq

    # Windows (con Chocolatey)

    choco install jq

    Uso básico:
    # Beautify archivo
    

    jq . archivo.json

    # Beautify y guardar

    jq . archivo.json > beautificado.json

    # Beautify desde string

    echo '{"nombre":"Ana","edad":28}' | jq .

    # Con indentación específica

    jq --indent 4 . archivo.json

    # Ordenar claves alfabéticamente

    jq -S . archivo.json

    Ejemplos avanzados:
    # Beautify solo parte del JSON
    

    jq '.usuarios' datos.json

    # Beautify y colorear

    jq -C . archivo.json

    # Beautify con filtro

    jq '.usuarios[] | select(.edad > 25)' datos.json

    Con Python

    Método 1: json.tool
    # Beautify archivo
    

    python -m json.tool archivo.json

    # Beautify y guardar

    python -m json.tool archivo.json beautificado.json

    # Con indentación personalizada

    python -c "import json, sys; print(json.dumps(json.load(sys.stdin), indent=4))" < archivo.json

    # Ordenar claves

    python -c "import json, sys; print(json.dumps(json.load(sys.stdin), indent=2, sort_keys=True))" < archivo.json

    Método 2: Script Python
    #!/usr/bin/env python3
    

    import json

    import sys

    def beautify_json(input_file, output_file=None, indent=2, sort_keys=False):

    with open(input_file, 'r', encoding='utf-8') as f:

    data = json.load(f)

    beautified = json.dumps(data, indent=indent, sort_keys=sort_keys, ensure_ascii=False)

    if output_file:

    with open(output_file, 'w', encoding='utf-8') as f:

    f.write(beautified)

    else:

    print(beautified)

    if __name__ == '__main__':

    if len(sys.argv) < 2:

    print("Uso: python beautify.py archivo.json [salida.json]")

    sys.exit(1)

    input_file = sys.argv[1]

    output_file = sys.argv[2] if len(sys.argv) > 2 else None

    beautify_json(input_file, output_file)

    Con Node.js

    Comando simple:
    node -e "console.log(JSON.stringify(require('./archivo.json'), null, 2))"
    Script reutilizable:
    #!/usr/bin/env node
    

    const fs = require('fs');

    const args = process.argv.slice(2);

    if (args.length === 0) {

    console.log('Uso: beautify archivo.json [salida.json]');

    process.exit(1);

    }

    const inputFile = args[0];

    const outputFile = args[1];

    try {

    const data = JSON.parse(fs.readFileSync(inputFile, 'utf8'));

    const beautified = JSON.stringify(data, null, 2);

    if (outputFile) {

    fs.writeFileSync(outputFile, beautified);

    console.log(✓ Guardado en ${outputFile});

    } else {

    console.log(beautified);

    }

    } catch (error) {

    console.error('Error:', error.message);

    process.exit(1);

    }

    Guardar como beautify.js y usar:

    chmod +x beautify.js
    

    ./beautify.js archivo.json salida.json

    Beautify Programáticamente

    JavaScript

    En navegador:
    // Beautify JSON string
    

    function beautifyJSON(jsonString, indent = 2) {

    try {

    const obj = JSON.parse(jsonString);

    return JSON.stringify(obj, null, indent);

    } catch (error) {

    console.error('JSON inválido:', error);

    return null;

    }

    }

    // Uso

    const minified = '{"nombre":"Ana","edad":28,"ciudad":"Madrid"}';

    const beautified = beautifyJSON(minified);

    console.log(beautified);

    // Con ordenamiento de claves

    function beautifyJSONSorted(jsonString, indent = 2) {

    const obj = JSON.parse(jsonString);

    return JSON.stringify(obj, Object.keys(obj).sort(), indent);

    }

    En Node.js:
    const fs = require('fs');
    
    

    function beautifyFile(inputPath, outputPath, options = {}) {

    const {

    indent = 2,

    sortKeys = false

    } = options;

    // Leer archivo

    const data = JSON.parse(fs.readFileSync(inputPath, 'utf8'));

    // Beautify

    const replacer = sortKeys ? Object.keys(data).sort() : null;

    const beautified = JSON.stringify(data, replacer, indent);

    // Guardar

    fs.writeFileSync(outputPath, beautified);

    console.log(✓ Beautificado: ${inputPath} → ${outputPath});

    }

    // Uso

    beautifyFile('input.json', 'output.json', {

    indent: 2,

    sortKeys: true

    });

    Python

    Script completo:
    import json
    

    from pathlib import Path

    def beautify_json(input_path, output_path=None, indent=2, sort_keys=False):

    """

    Beautifica archivo JSON

    Args:

    input_path: Ruta del archivo de entrada

    output_path: Ruta del archivo de salida (opcional)

    indent: Espacios de indentación

    sort_keys: Ordenar claves alfabéticamente

    """

    # Leer archivo

    with open(input_path, 'r', encoding='utf-8') as f:

    data = json.load(f)

    # Beautify

    beautified = json.dumps(

    data,

    indent=indent,

    sort_keys=sort_keys,

    ensure_ascii=False

    )

    # Guardar o imprimir

    if output_path:

    with open(output_path, 'w', encoding='utf-8') as f:

    f.write(beautified)

    print(f'✓ Guardado en {output_path}')

    else:

    print(beautified)

    # Uso

    beautify_json('input.json', 'output.json', indent=2, sort_keys=True)

    Beautify múltiples archivos:
    import json
    

    from pathlib import Path

    def beautify_directory(directory, pattern='.json', indent=2):

    """Beautifica todos los archivos JSON en un directorio"""

    path = Path(directory)

    for json_file in path.glob(pattern):

    try:

    # Leer

    with open(json_file, 'r', encoding='utf-8') as f:

    data = json.load(f)

    # Beautify y sobrescribir

    with open(json_file, 'w', encoding='utf-8') as f:

    json.dump(data, f, indent=indent, ensure_ascii=False)

    print(f'✓ Beautificado: {json_file.name}')

    except Exception as e:

    print(f'✗ Error en {json_file.name}: {e}')

    # Uso

    beautify_directory('./data', pattern='.json')

    Opciones de Beautification

    Indentación

    2 espacios (estándar web):
    {
    

    "nombre": "Ana",

    "datos": {

    "edad": 28

    }

    }

    4 espacios (Python, Java):
    {
    

    "nombre": "Ana",

    "datos": {

    "edad": 28

    }

    }

    Tabs:
    {
    

    "nombre": "Ana",

    "datos": {

    "edad": 28

    }

    }

    Ordenamiento de Claves

    Sin ordenar (orden original):
    {
    

    "z_ultima": "valor",

    "nombre": "Ana",

    "a_primera": "valor"

    }

    Ordenado alfabéticamente:
    {
    

    "a_primera": "valor",

    "nombre": "Ana",

    "z_ultima": "valor"

    }

    Longitud de Línea

    Sin límite:
    {
    

    "descripcion": "Esta es una descripción muy larga que continúa en una sola línea sin importar cuánto texto contenga"

    }

    Con wrap (usando herramientas especiales):
    {
    

    "descripcion": "Esta es una descripción muy larga que

    se envuelve en múltiples líneas para

    mejor legibilidad"

    }

    Automatización

    Git Pre-commit Hook

    #!/bin/bash
    

    # .git/hooks/pre-commit

    # Beautificar todos los archivos JSON staged

    for file in $(git diff --cached --name-only | grep '.json$'); do

    echo "Beautificando $file..."

    jq --indent 2 . "$file" > "$file.tmp"

    mv "$file.tmp" "$file"

    git add "$file"

    done

    NPM Script

    {
    

    "scripts": {

    "beautify": "prettier --write '*/.json'",

    "beautify:check": "prettier --check '*/.json'"

    },

    "devDependencies": {

    "prettier": "^3.0.0"

    }

    }

    GitHub Action

    name: Beautify JSON
    
    

    on: [push, pull_request]

    jobs:

    beautify:

    runs-on: ubuntu-latest

    steps:

    - uses: actions/checkout@v2

    - name: Setup Node.js

    uses: actions/setup-node@v2

    with:

    node-version: '18'

    - name: Install Prettier

    run: npm install -g prettier

    - name: Beautify JSON files

    run: prettier --write '*/.json'

    - name: Commit changes

    run: |

    git config --local user.email "action@github.com"

    git config --local user.name "GitHub Action"

    git add *.json

    git diff --quiet && git diff --staged --quiet || git commit -m "Beautify JSON files"

    git push

    Mejores Prácticas

    1. Usa Indentación Consistente

    // ✅ Bueno - 2 espacios consistente
    

    {

    "nivel1": {

    "nivel2": {

    "valor": "dato"

    }

    }

    }

    // ❌ Malo - Indentación mixta

    {

    "nivel1": {

    "nivel2": {

    "valor": "dato"

    }

    }

    }

    2. Beautifica Antes de Commit

    # Siempre beautifica antes de commit
    

    jq . archivo.json > temp.json && mv temp.json archivo.json

    git add archivo.json

    git commit -m "Actualizar configuración"

    3. Configura Editor para Auto-format

    // settings.json en VS Code
    

    {

    "editor.formatOnSave": true,

    "editor.defaultFormatter": "esbenp.prettier-vscode"

    }

    4. Valida Después de Beautificar

    # Beautificar y validar
    

    jq . archivo.json > beautificado.json && echo "✓ JSON válido"

    Conclusión

    JSON beautification es esencial para trabajar eficientemente con datos JSON. Ya sea usando herramientas online como Big JSON Viewer, editores de código, o scripts automatizados, tener JSON bien formateado mejora significativamente la legibilidad y mantenibilidad.

    Herramientas Recomendadas

    Uso Diario:
    • Visual Studio Code con Prettier
    • Big JSON Viewer para archivos grandes

    Línea de Comandos:
    • jq para Unix/Linux/Mac
    • Python json.tool multiplataforma

    Automatización:
    • Prettier con npm scripts
    • Git hooks para consistency

    ¡Mantén tu JSON beautificado y legible siempre!

    Share:

    Artículos Relacionados

    Read in English