← Torna al Blog

Come formattare JSON: Guida completa con strumenti e best practices

Impara a formattare JSON correttamente: indentazione, strumenti online e offline, prettification automatica, validazione e best practices professionali.

Big JSON Team12 min di letturatools
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.

12 min di lettura

# Come formattare JSON: Guida completa con strumenti e best practices

La formattazione corretta del JSON è essenziale per la leggibilità, la manutenibilità e il debug del codice. Questa guida ti insegnerà come formattare JSON in modo professionale utilizzando vari strumenti e tecniche.

Perché la formattazione JSON è importante

JSON non formattato vs formattato

❌ JSON non formattato (compresso):
{"utente":{"nome":"Marco","cognome":"Rossi","età":30,"indirizzo":{"via":"Via Roma 123","città":"Milano","cap":"20100"},"competenze":["JavaScript","Python","React"],"attivo":true}}
✅ JSON formattato correttamente:
{

"utente": {

"nome": "Marco",

"cognome": "Rossi",

"età": 30,

"indirizzo": {

"via": "Via Roma 123",

"città": "Milano",

"cap": "20100"

},

"competenze": [

"JavaScript",

"Python",

"React"

],

"attivo": true

}

}

Vantaggi della formattazione

  • Leggibilità migliorata: Facile identificare struttura e valori
  • Debug più semplice: Errori più facili da individuare
  • Collaborazione: Altri sviluppatori comprendono il codice rapidamente
  • Manutenzione: Modifiche più semplici e sicure
  • Validazione visiva: Struttura chiara a colpo d'occhio
  • Regole di formattazione JSON

    1. Indentazione

    Standard: 2 o 4 spazi
    {
    

    "livello1": {

    "livello2": {

    "livello3": "valore"

    }

    }

    }

    Tab vs Spazi: Preferisci gli spazi per coerenza cross-platform.

    2. Spazi attorno ai due punti

    Consigliato:

    {
    

    "chiave": "valore"

    }

    Da evitare:

    {
    

    "chiave":"valore"

    }

    3. Array su più righe

    Array brevi (< 3 elementi):
    {
    

    "colori": ["rosso", "verde", "blu"]

    }

    Array lunghi (≥ 3 elementi):
    {
    

    "linguaggi": [

    "JavaScript",

    "Python",

    "Java",

    "C++",

    "Go"

    ]

    }

    4. Oggetti annidati

    {
    

    "azienda": {

    "nome": "Tech Corp",

    "fondazione": 2020,

    "sede": {

    "via": "Via Milano 45",

    "città": "Torino",

    "cap": "10100",

    "coordinate": {

    "latitudine": 45.0703,

    "longitudine": 7.6869

    }

    },

    "dipendenti": [

    {

    "id": 1,

    "nome": "Laura Bianchi",

    "ruolo": "CEO"

    },

    {

    "id": 2,

    "nome": "Marco Verdi",

    "ruolo": "CTO"

    }

    ]

    }

    }

    5. Valori null e booleani

    {
    

    "attivo": true,

    "verificato": false,

    "telefono": null,

    "note": null

    }

    Formattazione con JavaScript

    Metodo 1: JSON.stringify() con parametri

    const dati = {
    

    nome: "Marco",

    età: 30,

    città: "Roma"

    };

    // Formatta con 2 spazi di indentazione

    const formattato = JSON.stringify(dati, null, 2);

    console.log(formattato);

    // Output:

    // {

    // "nome": "Marco",

    // "età": 30,

    // "città": "Roma"

    // }

    Parametri di JSON.stringify()

    JSON.stringify(valore, replacer, spazio)
    Parametro 1 - valore: L'oggetto da convertire Parametro 2 - replacer: Funzione di filtro (opzionale) Parametro 3 - spazio: Indentazione (numero di spazi o stringa)

    Esempi avanzati

    Indentazione con 4 spazi:
    const json = JSON.stringify(dati, null, 4);
    Indentazione con tab:
    const json = JSON.stringify(dati, null, '	');
    Filtro personalizzato:
    const utente = {
    

    nome: "Marco",

    password: "secret123",

    email: "marco@example.com"

    };

    // Escludi password dalla serializzazione

    const json = JSON.stringify(utente, (key, value) => {

    if (key === "password") return undefined;

    return value;

    }, 2);

    // Output: nome ed email, senza password

    Seleziona proprietà specifiche:
    const utente = {
    

    nome: "Marco",

    cognome: "Rossi",

    età: 30,

    password: "secret",

    indirizzoInterno: "dato sensibile"

    };

    // Include solo nome e cognome

    const json = JSON.stringify(utente, ["nome", "cognome"], 2);

    // Output:

    // {

    // "nome": "Marco",

    // "cognome": "Rossi"

    // }

    Funzione di formattazione personalizzata

    function formattaJSON(obj, options = {}) {
    

    const {

    indentazione = 2,

    ordinaChiavi = false,

    compatto = false

    } = options;

    // Ordina le chiavi se richiesto

    if (ordinaChiavi) {

    obj = ordinaOggettoRicorsivo(obj);

    }

    // Formatta

    const spazio = compatto ? 0 : indentazione;

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

    }

    function ordinaOggettoRicorsivo(obj) {

    if (typeof obj !== 'object' || obj === null) {

    return obj;

    }

    if (Array.isArray(obj)) {

    return obj.map(ordinaOggettoRicorsivo);

    }

    return Object.keys(obj)

    .sort()

    .reduce((risultato, chiave) => {

    risultato[chiave] = ordinaOggettoRicorsivo(obj[chiave]);

    return risultato;

    }, {});

    }

    // Uso

    const dati = {

    z: "ultimo",

    a: "primo",

    m: "medio"

    };

    console.log(formattaJSON(dati, { ordinaChiavi: true }));

    // Chiavi ordinate alfabeticamente

    Formattazione con Python

    Metodo 1: json.dumps()

    import json
    
    

    dati = {

    "nome": "Marco",

    "età": 30,

    "città": "Roma"

    }

    # Formatta con indentazione di 2 spazi

    formattato = json.dumps(dati, indent=2, ensure_ascii=False)

    print(formattato)

    # Output:

    # {

    # "nome": "Marco",

    # "età": 30,

    # "città": "Roma"

    # }

    Opzioni di formattazione Python

    import json
    
    

    dati = {

    "nome": "Marco",

    "cognome": "Rossi",

    "età": 30

    }

    # Ordina le chiavi alfabeticamente

    formattato = json.dumps(

    dati,

    indent=2,

    sort_keys=True,

    ensure_ascii=False

    )

    # Output con chiavi ordinate:

    # {

    # "cognome": "Rossi",

    # "età": 30,

    # "nome": "Marco"

    # }

    Salvataggio file formattato

    import json
    
    

    dati = {

    "configurazione": {

    "database": {

    "host": "localhost",

    "porta": 5432

    }

    }

    }

    # Salva in file con formattazione

    with open('config.json', 'w', encoding='utf-8') as file:

    json.dump(

    dati,

    file,

    indent=2,

    ensure_ascii=False,

    sort_keys=True

    )

    Funzione di formattazione personalizzata

    import json
    

    from decimal import Decimal

    def formatta_json(obj, kwargs):

    """

    Formatta JSON con opzioni personalizzate

    """

    class CustomEncoder(json.JSONEncoder):

    def default(self, obj):

    if isinstance(obj, Decimal):

    return float(obj)

    if isinstance(obj, set):

    return list(obj)

    return super().default(obj)

    default_options = {

    'indent': 2,

    'sort_keys': False,

    'ensure_ascii': False,

    'cls': CustomEncoder

    }

    default_options.update(kwargs)

    return json.dumps(obj, default_options)

    # Uso

    dati = {

    "prezzo": Decimal("99.99"),

    "tag": {"python", "json", "tutorial"}

    }

    print(formatta_json(dati, sort_keys=True))

    Strumenti da riga di comando

    1. Python - json.tool

    # Formatta file JSON
    

    python -m json.tool input.json output.json

    # Formatta con ordine chiavi

    python -m json.tool --sort-keys input.json

    # Formatta da stdin

    echo '{"nome":"Marco","età":30}' | python -m json.tool

    # Output formattato:

    # {

    # "nome": "Marco",

    # "età": 30

    # }

    2. jq - JSON processor

    # Formatta file JSON
    

    jq '.' input.json

    # Formatta con indentazione di 4 spazi

    jq --indent 4 '.' input.json

    # Ordina chiavi

    jq -S '.' input.json

    # Compatta (rimuovi formattazione)

    jq -c '.' input.json

    # Filtra e formatta

    jq '.utenti[] | select(.attivo == true)' dati.json

    3. Node.js

    // formatta.js
    

    const fs = require('fs');

    const input = process.argv[2];

    const output = process.argv[3] || input;

    const dati = JSON.parse(fs.readFileSync(input, 'utf8'));

    const formattato = JSON.stringify(dati, null, 2);

    fs.writeFileSync(output, formattato, 'utf8');

    console.log(File ${output} formattato!);

    Uso:

    node formatta.js input.json output.json

    Strumenti online

    1. JSON Formatter & Validator

    • URL: jsonformatter.org
    • Caratteristiche: Formattazione, validazione, minificazione
    • Pro: Semplice, veloce
    • Contro: Richiede connessione internet

    2. JSON Simplify (nostro tool!)

    • Caratteristiche:
    - Formattazione in tempo reale

    - Path finder

    - Tree viewer

    - Validazione istantanea

    3. JSONLint

    • URL: jsonlint.com
    • Caratteristiche: Validazione e formattazione
    • Pro: Messaggi di errore dettagliati

    4. VS Code Online

    • URL: vscode.dev
    • Caratteristiche: Editor completo con syntax highlighting

    Editor di codice e IDE

    Visual Studio Code

    Formattazione automatica:
  • Apri file .json
  • Premi Shift + Alt + F (Windows/Linux)
  • Oppure Shift + Option + F (Mac)
  • Oppure: Click destro → "Format Document"
  • Configurazione VS Code (settings.json):
    {
    

    "editor.formatOnSave": true,

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

    "[json]": {

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

    "editor.tabSize": 2,

    "editor.insertSpaces": true

    },

    "json.format.enable": true,

    "json.format.keepLines": false

    }

    Prettier (formattatore)

    Installazione:
    npm install --save-dev prettier
    Configurazione (.prettierrc):
    {
    

    "tabWidth": 2,

    "useTabs": false,

    "semi": true,

    "singleQuote": false,

    "trailingComma": "none",

    "bracketSpacing": true,

    "arrowParens": "always"

    }

    Uso:
    # Formatta un file
    

    npx prettier --write data.json

    # Formatta tutti i file JSON

    npx prettier --write "*/.json"

    # Controlla senza modificare

    npx prettier --check data.json

    Sublime Text

  • Installa plugin "Pretty JSON"
  • Seleziona testo JSON
  • Ctrl + Alt + J per formattare
  • IntelliJ IDEA / WebStorm

  • Apri file JSON
  • Ctrl + Alt + L (Windows/Linux)
  • Cmd + Option + L (Mac)
  • Formattazione compatta vs leggibile

    JSON compatto (minified)

    Quando usare:
    • Trasmissione dati via rete
    • Riduzione dimensione file
    • API response (produzione)

    // Compatta JSON
    

    const compatto = JSON.stringify(dati);

    // {"nome":"Marco","età":30,"città":"Roma"}

    // File size ridotto del 40-60%

    JSON leggibile (prettified)

    Quando usare:
    • Sviluppo
    • Debug
    • File di configurazione
    • Documentazione

    // JSON formattato
    

    const leggibile = JSON.stringify(dati, null, 2);

    // {

    // "nome": "Marco",

    // "età": 30,

    // "città": "Roma"

    // }

    Best practices per la formattazione

    1. Usa indentazione consistente

    Buono:

    {
    

    "livello1": {

    "livello2": {

    "valore": "consistente"

    }

    }

    }

    Da evitare:

    {
    

    "livello1": {

    "livello2": {

    "valore": "inconsistente"

    }

    }

    }

    2. Ordina le chiavi logicamente

    {
    

    "id": 1,

    "nome": "Marco",

    "cognome": "Rossi",

    "contatti": {

    "email": "marco@example.com",

    "telefono": "+39 123 456 7890"

    },

    "creato_il": "2026-01-26",

    "modificato_il": "2026-01-26"

    }

    3. Raggruppa dati correlati

    {
    

    "informazioni_personali": {

    "nome": "Marco",

    "cognome": "Rossi",

    "data_nascita": "1994-05-15"

    },

    "contatti": {

    "email": "marco@example.com",

    "telefono": "+39 123 456 7890"

    },

    "preferenze": {

    "lingua": "it",

    "tema": "scuro"

    }

    }

    4. Usa nomi di chiave descrittivi

    Buono:

    {
    

    "indirizzo_email": "marco@example.com",

    "numero_telefono": "+39 123 456 7890",

    "data_registrazione": "2026-01-26"

    }

    Da evitare:

    {
    

    "em": "marco@example.com",

    "tel": "+39 123 456 7890",

    "reg": "2026-01-26"

    }

    5. Evita annidamenti eccessivi

    Troppo profondo (7 livelli):

    {
    

    "a": {

    "b": {

    "c": {

    "d": {

    "e": {

    "f": {

    "g": "troppo annidato!"

    }

    }

    }

    }

    }

    }

    }

    Meglio (3-4 livelli max):

    {
    

    "configurazione": {

    "database": {

    "connessione": {

    "host": "localhost",

    "porta": 5432

    }

    }

    }

    }

    Validazione durante la formattazione

    Script di formattazione e validazione

    const fs = require('fs');
    
    

    function formattaEValida(filePath) {

    try {

    // Leggi file

    const contenuto = fs.readFileSync(filePath, 'utf8');

    // Valida (questo lancerà errore se non valido)

    const dati = JSON.parse(contenuto);

    // Formatta

    const formattato = JSON.stringify(dati, null, 2);

    // Salva

    fs.writeFileSync(filePath, formattato, 'utf8');

    console.log(✅ ${filePath} formattato e validato con successo!);

    return true;

    } catch (errore) {

    console.error(❌ Errore in ${filePath}:);

    console.error(errore.message);

    return false;

    }

    }

    // Formatta tutti i file JSON in una directory

    function formattaDirectory(dirPath) {

    const files = fs.readdirSync(dirPath);

    files.forEach(file => {

    if (file.endsWith('.json')) {

    formattaEValida(${dirPath}/${file});

    }

    });

    }

    // Uso

    formattaDirectory('./data');

    Pre-commit hook (Git)

    Crea .git/hooks/pre-commit:

    #!/bin/bash
    
    

    # Formatta tutti i file JSON staged

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

    # Formatta con jq

    jq '.' "$file" > "$file.tmp" && mv "$file.tmp" "$file"

    # Aggiungi di nuovo allo staging

    git add "$file"

    done

    Troubleshooting

    Problema: JSON non si formatta

    Causa: Errore di sintassi nel JSON Soluzione:
    // Usa try-catch per identificare l'errore
    

    try {

    const dati = JSON.parse(jsonString);

    const formattato = JSON.stringify(dati, null, 2);

    } catch (errore) {

    console.error('Errore di parsing:', errore.message);

    // Output: "Unexpected token } in JSON at position 45"

    }

    Problema: Caratteri speciali non visualizzati

    Soluzione Python:
    # Usa ensure_ascii=False
    

    json.dumps(dati, indent=2, ensure_ascii=False)

    Soluzione JavaScript:
    // JavaScript gestisce Unicode correttamente di default
    

    JSON.stringify({ nome: "Café ☕" }, null, 2);

    Conclusione

    La formattazione corretta del JSON è fondamentale per:

    • Leggibilità: Codice più chiaro e comprensibile
    • Manutenibilità: Modifiche più semplici e sicure
    • Collaborazione: Team work più efficace
    • Debug: Problemi più facili da identificare

    Riepilogo strumenti

    Online: JSON Simplify, JSONLint, JSONFormatter Riga di comando: jq, python -m json.tool Editor: VS Code, Sublime Text, WebStorm Librerie: Prettier, ESLint

    Scegli lo strumento più adatto al tuo workflow e mantieni sempre il JSON formattato correttamente!

    Share:

    Articoli Correlati

    Read in English