Errori JSON comuni e come risolverli: Guida troubleshooting
Guida completa agli errori JSON più comuni: syntax errors, unexpected token, parsing failures. Cause, soluzioni, strumenti di debugging 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.
# Errori JSON comuni e come risolverli
Gli errori JSON possono essere frustranti, ma la maggior parte sono facili da risolvere una volta capiti. Questa guida ti mostrerà gli errori più comuni, le loro cause e le soluzioni.
Errore #1: Unexpected token
Messaggio errore
SyntaxError: Unexpected token } in JSON at position 45
SyntaxError: Unexpected token , in JSON at position 23
Cause comuni
1. Virgola finale (trailing comma)❌ Errato:
{
"nome": "Marco",
"età": 30,
}
✅ Corretto:
{
"nome": "Marco",
"età": 30
}
2. Virgola mancante
❌ Errato:
{
"nome": "Marco"
"età": 30
}
✅ Corretto:
{
"nome": "Marco",
"età": 30
}
3. Virgola in array
❌ Errato:
{
"tag": ["uno", "due",]
}
✅ Corretto:
{
"tag": ["uno", "due"]
}
Soluzione
Strumenti:- JSONLint (jsonlint.com) - Mostra posizione esatta errore
- VS Code - Evidenzia errori in tempo reale
- jq - Valida da command line
# Valida con jq
jq '.' file.json
# Se valido, stampa formattato
# Se invalido, mostra errore specifico
Errore #2: Virgolette singole
Messaggio errore
SyntaxError: Unexpected token ' in JSON
Causa
JSON richiede SEMPRE virgolette doppie ("), mai singole (').
❌ Errato:
{
'nome': 'Marco',
'età': 30
}
✅ Corretto:
{
"nome": "Marco",
"età": 30
}
Soluzione
Find & replace:// In editor
// Find: '
// Replace: "
// In JavaScript (escape stringhe con ')
const fixed = jsonString.replace(/'/g, '"');
Attenzione ai valori:
{
"messaggio": "Non usare ' nel JSON"
}
Errore #3: Chiavi senza virgolette
Messaggio errore
SyntaxError: Unexpected token n in JSON
Causa
Le chiavi devono essere stringhe tra virgolette doppie.
❌ Errato (stile JavaScript):
{
nome: "Marco",
età: 30
}
✅ Corretto:
{
"nome": "Marco",
"età": 30
}
Soluzione JavaScript → JSON
Usa JSON.stringify:// JavaScript object
const obj = {
nome: "Marco",
età: 30
};
// Converti in JSON valido
const json = JSON.stringify(obj);
console.log(json);
// {"nome":"Marco","età":30}
Errore #4: Commenti in JSON
Messaggio errore
SyntaxError: Unexpected token / in JSON
Causa
JSON non supporta commenti.
❌ Errato:
{
// Questo è un commento
"nome": "Marco",
/ Commento
multi-riga /
"età": 30
}
Soluzioni
1. Rimuovi commenti✅ JSON puro:
{
"nome": "Marco",
"età": 30
}
2. Usa campo dedicato
✅ Metadati:
{
"_comment": "Configurazione utente",
"nome": "Marco",
"età": 30
}
3. Usa JSON5 o JSONC
JSON5 (con commenti):
{
// Commenti supportati!
nome: "Marco", // Chiavi senza virgolette OK
età: 30, // Virgole finali OK
}
JSONC (VS Code config):
{
// settings.json di VS Code
"editor.fontSize": 14,
"editor.tabSize": 2
}
Errore #5: Valori non quotati
Messaggio errore
SyntaxError: Unexpected token u in JSON
Causa
Valori undefined, funzioni, etc. non sono JSON valido.
❌ Errato:
{
"nome": undefined,
"callback": function() {}
}
✅ Corretto:
{
"nome": null,
"descrizione": "callback non supportata in JSON"
}
Tipi validi in JSON
✅ Supportati:
string:"testo"number:42,3.14boolean:true,falsenull:nullarray:[1, 2, 3]object:{"chiave": "valore"}
❌ Non supportati:
undefinedNaNInfinity- Funzioni
- Date objects (usa stringa ISO)
- RegExp
Conversione Date
❌ Errato:
const data = {
createdAt: new Date()
};
JSON.stringify(data);
// {"createdAt":"2026-01-26T10:00:00.000Z"} ✅ Stringa
✅ Esplicito:
const data = {
createdAt: new Date().toISOString()
};
Errore #6: Parentesi non bilanciate
Messaggio errore
SyntaxError: Unexpected end of JSON input
Causa
Parentesi graffe o quadre non chiuse.
❌ Errato:
{
"utente": {
"nome": "Marco"
}
// } mancante!
❌ Array non chiuso:
{
"tag": ["uno", "due", "tre"
// ] mancante!
}
Soluzione
Conta parentesi:{ = aperta
} = chiusa
Devono essere uguali!
Usa editor con bracket matching:
- VS Code evidenzia coppie
- Notepad++ mostra matching
- Sublime Text indica errori
# jq mostra dove manca parentesi
jq '.' broken.json
parse error: Expected separator between values at line 5, column 1
Errore #7: Encoding problemi
Messaggio errore
SyntaxError: Unexpected token � in JSON
Causa
File non UTF-8 o BOM (Byte Order Mark).
Soluzione
1. Salva come UTF-8 VS Code:- Click encoding in barra stato
- "Save with Encoding" → UTF-8
- Encoding → UTF-8 (without BOM)
# Linux/Mac
sed '1s/^\xEF\xBB\xBF//' file.json > fixed.json
# PowerShell
$content = Get-Content file.json -Raw
$content = $content.TrimStart("\uFEFF")
$content | Out-File -Encoding UTF8 fixed.json
Errore #8: Caratteri speciali
Causa
Caratteri speciali non escaped.
❌ Errato:
{
"path": "C:\Users\Marco",
"messaggio": "Dice: "Ciao!""
}
✅ Corretto:
{
"path": "C:\\Users\\Marco",
"messaggio": "Dice: \"Ciao!\""
}
Caratteri da escapare
"→\\"- Virgolette doppie\\→\\\\- Backslash/→\\/- Slash (opzionale)\\b→ Backspace\\f→ Form feed\\n→ Nuova linea\\r→ Carriage return\\t→ Tabulazione
Escape automatico
const obj = {
path: "C:\Users\Marco",
messaggio: 'Dice: "Ciao!"'
};
// JSON.stringify fa escape automatico!
const json = JSON.stringify(obj, null, 2);
console.log(json);
/
{
"path": "C:\\Users\\Marco",
"messaggio": "Dice: \"Ciao!\""
}
/
Errore #9: Numeri non validi
Causa
Numeri con formato non valido.
❌ Errato:
{
"prezzo": .99,
"sconto": 15.,
"hex": 0xFF,
"infinito": Infinity
}
✅ Corretto:
{
"prezzo": 0.99,
"sconto": 15.0,
"hex": 255,
"infinito": null
}
Numeri speciali
NaN e Infinity:const data = {
result: NaN,
max: Infinity
};
JSON.stringify(data);
// {"result":null,"max":null}
// Meglio usare stringhe
const betterData = {
result: "NaN",
max: "Infinity"
};
Errore #10: JSON troppo profondo
Messaggio errore
RangeError: Maximum call stack size exceeded
Causa
Riferimenti circolari o nesting eccessivo.
❌ Riferimento circolare:
const obj = { nome: "Marco" };
obj.self = obj; // Punta a se stesso!
JSON.stringify(obj);
// TypeError: Converting circular structure to JSON
Soluzioni
1. Rimuovi circolarità:const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return "[Circular]";
}
seen.add(value);
}
return value;
};
};
const json = JSON.stringify(obj, getCircularReplacer());
2. Usa librerie:
import stringify from 'json-stringify-safe';
const json = stringify(objWithCircular);
3. Limita profondità:
function stringifyLimited(obj, maxDepth = 10) {
let depth = 0;
return JSON.stringify(obj, (key, value) => {
depth++;
if (depth > maxDepth) return "[Too deep]";
depth--;
return value;
});
}
Strumenti di debugging
Online validators
1. JSONLint (jsonlint.com)- Mostra errori con linea
- Formatta JSON
- Spiega problema
- Tree view
- Error highlighting
- Validation
Browser DevTools
Console:// Test parsing
try {
JSON.parse(jsonString);
console.log("✅ JSON valido");
} catch (e) {
console.error("❌ Errore:", e.message);
console.error("Posizione:", e.message.match(/position (\d+)/)?.[1]);
}
VS Code
Built-in validation:- Errori mostrati in tempo reale
- Hover per dettagli
- Auto-fix per problemi comuni
- JSON Tools - Format, minify, validate
- Prettier - Auto-format on save
Command line
jq:# Valida
jq empty file.json
# Se valido: nessun output
# Se invalido: mostra errore dettagliato
Python:
python -m json.tool file.json
# Se invalido, mostra errore con linea
Best practices per evitare errori
1. Usa JSON.stringify per generare
❌ String concatenation:
const json = '{"nome":"' + nome + '"}'; // Pericoloso!
✅ JSON.stringify:
const json = JSON.stringify({ nome });
2. Valida prima di parsare
function safeParseJSON(str) {
try {
return { success: true, data: JSON.parse(str) };
} catch (e) {
return { success: false, error: e.message };
}
}
const result = safeParseJSON(jsonString);
if (result.success) {
console.log(result.data);
} else {
console.error("Parse failed:", result.error);
}
3. Usa linter/formatter
Prettier config:{
"printWidth": 80,
"tabWidth": 2,
"useTabs": false
}
ESLint:
{
"rules": {
"quote-props": ["error", "always"],
"comma-dangle": ["error", "never"]
}
}
4. Test con dati reali
// Test suite
describe('JSON parsing', () => {
it('handles valid JSON', () => {
const json = '{"nome":"Marco"}';
expect(() => JSON.parse(json)).not.toThrow();
});
it('rejects trailing comma', () => {
const json = '{"nome":"Marco",}';
expect(() => JSON.parse(json)).toThrow();
});
});
Conclusione
Errori più comuni:- JSONLint per validation
- VS Code per editing
- jq per command line
- JSON.stringify per generazione
Usa sempre JSON.stringify() per generare JSON, mai concatenazione manuale di stringhe!
Articoli Correlati
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.
JavaScript e JSON: Guida completa a JSON.parse() e JSON.stringify()
Guida completa su JSON in JavaScript: parsing, serializzazione, gestione errori, localStorage, fetch API e best practices. Include esempi pratici e troubleshooting.