Guida JSON Beautifier: Formattazione professionale del codice
Impara a utilizzare JSON beautifier per formattare, abbellire e rendere leggibile il codice JSON. Strumenti, tecniche e best practices.
Big JSON Team
• Technical WriterExpert in JSON data manipulation, API development, and web technologies. Passionate about creating tools that make developers' lives easier.
# Guida JSON Beautifier: Formattazione professionale del codice
Un JSON beautifier (o prettifier) trasforma JSON compatto e difficile da leggere in codice ben formattato e leggibile. Questa guida ti insegnerà tutto sui JSON beautifier e come usarli efficacemente.
Cos'è un JSON Beautifier?
Un JSON beautifier è uno strumento che:
- Formatta JSON compatto aggiungendo indentazione
- Valida la sintassi JSON
- Evidenzia la struttura dei dati
- Rende leggibile il codice per gli umani
Prima e dopo: Il potere del beautifier
Prima (JSON compatto)
{"utente":{"id":12345,"nome":"Marco","cognome":"Rossi","contatti":{"email":"marco.rossi@example.com","telefono":"+39 02 1234 5678","indirizzo":{"via":"Via Milano 45","città":"Torino","cap":"10100"}},"ruoli":["admin","editor"],"attivo":true,"ultimo_accesso":"2026-01-26T10:30:00Z"}}
Dopo (JSON beautified)
{
"utente": {
"id": 12345,
"nome": "Marco",
"cognome": "Rossi",
"contatti": {
"email": "marco.rossi@example.com",
"telefono": "+39 02 1234 5678",
"indirizzo": {
"via": "Via Milano 45",
"città": "Torino",
"cap": "10100"
}
},
"ruoli": [
"admin",
"editor"
],
"attivo": true,
"ultimo_accesso": "2026-01-26T10:30:00Z"
}
}
Miglioramento: +300% in leggibilità!
Quando usare un JSON Beautifier
✅ Scenari comuni
// Response da API (minified)
fetch('https://api.example.com/user/123')
.then(r => r.text())
.then(text => {
console.log(text);
// {"id":123,"name":"Marco","email":"..."}
// Difficile da leggere!
});
// package.json scaricato da npm (compatto)
{"name":"my-app","version":"1.0.0","dependencies":{"react":"^18.0.0","typescript":"^5.0.0"}}
// Payload POST da debuggare
const payload = '{"order":{"id":"ORD-001","items":[{"sku":"ABC","qty":2}]}}';
// Beautify per capire la struttura!
const data = localStorage.getItem('userPreferences');
console.log(data);
// {"theme":"dark","lang":"it","notifications":{"email":true}}
[2026-01-26 10:30:45] INFO: {"event":"user_login","user_id":123,"ip":"192.168.1.1","timestamp":1706267445000}
Tipi di JSON Beautifier
1. Beautifier Online
Vantaggi:- Nessuna installazione
- Accesso da browser
- Aggiornamenti automatici
- Richiede internet
- Privacy dei dati
- JSON Simplify
- JSONLint
- JSONFormatter.org
2. Beautifier da riga di comando
JavaScript (Node.js):// beautify.js
const fs = require('fs');
const json = fs.readFileSync('input.json', 'utf8');
const beautified = JSON.stringify(JSON.parse(json), null, 2);
fs.writeFileSync('output.json', beautified);
Uso:
node beautify.js
Python:
import json
# Leggi JSON compatto
with open('input.json', 'r') as f:
data = json.load(f)
# Scrivi JSON beautified
with open('output.json', 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
jq (Linux/Mac):
# Beautify con jq
jq '.' input.json > output.json
# Beautify da stdin
echo '{"nome":"Marco"}' | jq '.'
# Output:
# {
# "nome": "Marco"
# }
3. Beautifier in IDE
Visual Studio Code:1. Apri file .json
Shift + Alt + F (Windows/Linux)
Shift + Option + F (Mac)
Oppure: Click destro → Format Document
Configurazione VS Code:
{
"editor.formatOnSave": true,
"[json]": {
"editor.defaultFormatter": "vscode.json-language-features",
"editor.tabSize": 2
}
}
Sublime Text:
- Installa "Pretty JSON" package
- Seleziona JSON
- Ctrl+Alt+J (Windows/Linux)
- Cmd+Ctrl+J (Mac)
- Ctrl+Alt+L (Windows/Linux)
- Cmd+Option+L (Mac)
4. Librerie di programmazione
JavaScript - prettier:npm install --save-dev prettier
const prettier = require('prettier');
const uglyJson = '{"nome":"Marco","età":30}';
const beautiful = prettier.format(uglyJson, {
parser: 'json',
tabWidth: 2,
useTabs: false
});
console.log(beautiful);
// {
// "nome": "Marco",
// "età": 30
// }
Python - json.tool:
# Da riga di comando
python -m json.tool input.json output.json
# Con sort delle chiavi
python -m json.tool --sort-keys input.json
Opzioni di formattazione
1. Indentazione
2 spazi (consigliato per web):{
"nome": "Marco",
"età": 30
}
4 spazi (consigliato per Python):
{
"nome": "Marco",
"età": 30
}
Tab:
const json = JSON.stringify(data, null, '\t');
2. Compattazione array
Array su singola riga (brevi):{
"colori": ["rosso", "verde", "blu"]
}
Array multi-riga (lunghi):
{
"linguaggi": [
"JavaScript",
"Python",
"Java",
"C++",
"Go"
]
}
3. Ordinamento chiavi
// JavaScript con ordinamento
function beautifyWithSort(obj) {
const sortedKeys = {};
Object.keys(obj).sort().forEach(key => {
sortedKeys[key] = obj[key];
});
return JSON.stringify(sortedKeys, null, 2);
}
const data = { z: 3, a: 1, m: 2 };
console.log(beautifyWithSort(data));
// {
// "a": 1,
// "m": 2,
// "z": 3
// }
# Python con ordinamento
import json
data = {"z": 3, "a": 1, "m": 2}
print(json.dumps(data, indent=2, sort_keys=True))
4. Gestione caratteri speciali
// JavaScript - mantieni caratteri Unicode
const data = { città: "Milano", messaggio: "Ciao! 👋" };
// Senza ensure_ascii
console.log(JSON.stringify(data, null, 2));
// {
// "città": "Milano",
// "messaggio": "Ciao! 👋"
// }
# Python - mantieni caratteri Unicode
import json
data = {"città": "Milano", "messaggio": "Ciao! 👋"}
print(json.dumps(data, indent=2, ensure_ascii=False))
Funzioni di Beautifier personalizzate
JavaScript: Beautifier avanzato
class JSONBeautifier {
constructor(options = {}) {
this.indent = options.indent || 2;
this.sortKeys = options.sortKeys || false;
this.maxLineLength = options.maxLineLength || 80;
}
beautify(obj) {
// Ordina chiavi se richiesto
if (this.sortKeys) {
obj = this._sortObjectKeys(obj);
}
// Stringifica con indentazione
let json = JSON.stringify(obj, null, this.indent);
// Compatta array brevi su singola riga
json = this._compactShortArrays(json);
return json;
}
_sortObjectKeys(obj) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
if (Array.isArray(obj)) {
return obj.map(item => this._sortObjectKeys(item));
}
const sorted = {};
Object.keys(obj).sort().forEach(key => {
sorted[key] = this._sortObjectKeys(obj[key]);
});
return sorted;
}
_compactShortArrays(json) {
// Compatta array con pochi elementi semplici
return json.replace(
/\[\n\s+("(?:\\.|[^"\\])"|\d+|true|false|null)(?:,\n\s+("(?:\\.|[^"\\])"|\d+|true|false|null))\n\s+\]/g,
match => {
// Se l'array è breve, compatta
const items = match.match(/"(?:\\.|[^"\\])"|\d+|true|false|null/g);
if (items && items.length <= 3) {
return '[' + items.join(', ') + ']';
}
return match;
}
);
}
minify(obj) {
return JSON.stringify(obj);
}
}
// Uso
const beautifier = new JSONBeautifier({
indent: 2,
sortKeys: true,
maxLineLength: 80
});
const data = {
nome: "Marco",
hobby: ["lettura", "sport"],
città: "Milano"
};
console.log(beautifier.beautify(data));
Python: Beautifier personalizzato
import json
from typing import Any, Optional
class JSONBeautifier:
def __init__(self, indent: int = 2, sort_keys: bool = False):
self.indent = indent
self.sort_keys = sort_keys
def beautify(self, obj: Any) -> str:
"""Beautify JSON object"""
return json.dumps(
obj,
indent=self.indent,
sort_keys=self.sort_keys,
ensure_ascii=False
)
def beautify_file(self, input_file: str, output_file: Optional[str] = None):
"""Beautify JSON file"""
with open(input_file, 'r', encoding='utf-8') as f:
data = json.load(f)
beautified = self.beautify(data)
if output_file:
with open(output_file, 'w', encoding='utf-8') as f:
f.write(beautified)
else:
print(beautified)
def minify(self, obj: Any) -> str:
"""Minify JSON object"""
return json.dumps(obj, separators=(',', ':'), ensure_ascii=False)
# Uso
beautifier = JSONBeautifier(indent=2, sort_keys=True)
data = {
"nome": "Marco",
"città": "Milano",
"età": 30
}
print(beautifier.beautify(data))
Beautify con sintassi highlighting
Browser (HTML + JavaScript)
<!DOCTYPE html>
<html>
<head>
<style>
.json-key { color: #881391; }
.json-string { color: #1A1AA6; }
.json-number { color: #1C00CF; }
.json-boolean { color: #0000FF; }
.json-null { color: #808080; }
</style>
</head>
<body>
<pre id="output"></pre>
<script>
function highlightJSON(json) {
json = JSON.stringify(JSON.parse(json), null, 2);
// Syntax highlighting
json = json.replace(
/("(\u[a-zA-Z0-9]{4}|\[^u]|[^\"])"(\s:)?|\b(true|false|null)\b|-?\d+(?:\.\d)?(?:[eE][+\-]?\d+)?)/g,
match => {
let cls = 'json-number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'json-key';
} else {
cls = 'json-string';
}
} else if (/true|false/.test(match)) {
cls = 'json-boolean';
} else if (/null/.test(match)) {
cls = 'json-null';
}
return <span class="${cls}">${match}</span>;
}
);
return json;
}
const data = '{"nome":"Marco","età":30,"attivo":true}';
document.getElementById('output').innerHTML = highlightJSON(data);
</script>
</body>
</html>
Beautifier per API Response
Fetch + Beautify
async function fetchAndBeautify(url) {
try {
const response = await fetch(url);
const data = await response.json();
// Beautify la response
const beautiful = JSON.stringify(data, null, 2);
console.log(beautiful);
return data;
} catch (error) {
console.error('Errore:', error);
}
}
// Uso
fetchAndBeautify('https://api.example.com/users/123');
Axios + Beautify
const axios = require('axios');
axios.get('https://api.example.com/users/123')
.then(response => {
// Response già in oggetto JavaScript
console.log(JSON.stringify(response.data, null, 2));
})
.catch(error => console.error(error));
Con interceptor (beautify tutte le response)
axios.interceptors.response.use(
response => {
// Beautify e log tutte le response
console.log('Response beautified:');
console.log(JSON.stringify(response.data, null, 2));
return response;
},
error => Promise.reject(error)
);
Batch beautification
Beautify tutti i file in una directory
// beautify-all.js
const fs = require('fs');
const path = require('path');
function beautifyDirectory(dirPath) {
const files = fs.readdirSync(dirPath);
files.forEach(file => {
if (file.endsWith('.json')) {
const filePath = path.join(dirPath, file);
try {
// Leggi
const content = fs.readFileSync(filePath, 'utf8');
const data = JSON.parse(content);
// Beautify
const beautiful = JSON.stringify(data, null, 2);
// Sovrascrivi
fs.writeFileSync(filePath, beautiful, 'utf8');
console.log(✅ Beautified: ${file});
} catch (error) {
console.error(❌ Errore in ${file}:, error.message);
}
}
});
}
// Uso
beautifyDirectory('./data');
# Uso
node beautify-all.js
Script Python per batch
import os
import json
from pathlib import Path
def beautify_directory(dir_path: str):
"""Beautify tutti i file JSON in una directory"""
for file_path in Path(dir_path).glob('.json'):
try:
with open(file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
with open(file_path, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
print(f'✅ Beautified: {file_path.name}')
except Exception as e:
print(f'❌ Errore in {file_path.name}: {str(e)}')
# Uso
beautify_directory('./data')
Git hooks per auto-beautify
Pre-commit hook
``.git/hooks/pre-commit
#!/bin/bash
# Beautify tutti i file JSON staged
echo "Beautifying JSON files..."
for file in $(git diff --cached --name-only --diff-filter=ACM | grep '\.json$'); do
echo "Formatting $file"
# Usa jq per beautify
jq '.' "$file" > "$file.tmp" && mv "$file.tmp" "$file"
# Re-stage il file
git add "$file"
done
echo "JSON beautification complete!"
Rendi eseguibile:bash
chmod +x .git/hooks/pre-commit
<h2 id="troubleshooting" class="text-2xl font-bold mt-10 mb-5 text-foreground border-b border-gray-200 dark:border-gray-700 pb-2">Troubleshooting</h2>
<h3 id="problema-1-json-non-valido" class="text-xl font-semibold mt-8 mb-4 text-foreground">Problema 1: JSON non valido</h3>
Errore: Unexpected token } in JSON at position 45
Soluzione:javascript
function safeBeautify(jsonString) {
try {
const obj = JSON.parse(jsonString);
return JSON.stringify(obj, null, 2);
} catch (error) {
console.error('JSON non valido:', error.message);
// Mostra posizione errore
const pos = parseInt(error.message.match(/\d+/)?.[0] || 0);
const context = jsonString.substring(Math.max(0, pos - 20), pos + 20);
console.error('Contesto:', context);
return null;
}
}
<h3 id="problema-2-file-troppo-grande" class="text-xl font-semibold mt-8 mb-4 text-foreground">Problema 2: File troppo grande</h3>javascript
// Beautify file grandi con stream
const fs = require('fs');
const { Transform } = require('stream');
class JSONBeautifyStream extends Transform {
_transform(chunk, encoding, callback) {
try {
const obj = JSON.parse(chunk);
const beautified = JSON.stringify(obj, null, 2);
callback(null, beautified);
} catch (error) {
callback(error);
}
}
}
// Uso
fs.createReadStream('large.json')
.pipe(new JSONBeautifyStream())
.pipe(fs.createWriteStream('large-beautified.json'));
<h3 id="problema-3-caratteri-speciali-persi" class="text-xl font-semibold mt-8 mb-4 text-foreground">Problema 3: Caratteri speciali persi</h3>python
# Usa ensure_ascii=False in Python
import json
data = {"città": "Milano", "caffè": "espresso"}
# ❌ Sbagliato
print(json.dumps(data, indent=2))
# {"citt\u00e0": "Milano"}
# ✅ Corretto
print(json.dumps(data, indent=2, ensure_ascii=False))
# {"città": "Milano"}
<h2 id="best-practices" class="text-2xl font-bold mt-10 mb-5 text-foreground border-b border-gray-200 dark:border-gray-700 pb-2">Best practices</h2>
<h3 id="1-valida-prima-di-beautify" class="text-xl font-semibold mt-8 mb-4 text-foreground">1. Valida prima di beautify</h3>
javascript
function validateAndBeautify(jsonString) {
try {
const obj = JSON.parse(jsonString);
return {
valid: true,
beautified: JSON.stringify(obj, null, 2)
};
} catch (error) {
return {
valid: false,
error: error.message
};
}
}
<h3 id="2-mantieni-backup" class="text-xl font-semibold mt-8 mb-4 text-foreground">2. Mantieni backup</h3>javascript
function safeBeautifyFile(filePath) {
// Backup
fs.copyFileSync(filePath, ${filePath}.backup);
try {
const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
const beautiful = JSON.stringify(data, null, 2);
fs.writeFileSync(filePath, beautiful);
// Rimuovi backup se successo
fs.unlinkSync(${filePath}.backup);
} catch (error) {
// Ripristina da backup
fs.copyFileSync(${filePath}.backup, filePath);
throw error;
}
}
<h3 id="3-usa-editorconfig" class="text-xl font-semibold mt-8 mb-4 text-foreground">3. Usa .editorconfig</h3>ini
# .editorconfig
[*.json]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
``
Conclusione
JSON beautifier sono strumenti essenziali per:
- ✅ Rendere JSON leggibile
- ✅ Debug più semplice
- ✅ Manutenzione codice
- ✅ Collaborazione team
- ✅ Validazione visiva
- Online: JSON Simplify
- CLI: jq, python -m json.tool
- IDE: VS Code con Prettier
- Librerie: prettier (JS), json module (Python)
Beautify sempre il tuo JSON per codice più pulito e professionale!
Articoli Correlati
Cos'è JSON? Guida completa per principianti
Scopri cos'è JSON, la sua sintassi, i tipi di dati e i casi d'uso. Una guida completa e adatta ai principianti per comprendere JavaScript Object Notation.
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.
Migliori strumenti JSON online 2026: Guida completa
Scopri i migliori strumenti JSON online per formattare, validare, convertire e visualizzare JSON. Confronto dettagliato con esempi pratici.