← Torna al Blog

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 Team15 min di letturatroubleshooting
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.

15 min di lettura

# 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

Command line check:
# 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.14
  • boolean: true, false
  • null: null
  • array: [1, 2, 3]
  • object: {"chiave": "valore"}

Non supportati:

  • undefined
  • NaN
  • Infinity
  • 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

Tool online:
# 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

Notepad++:
  • Encoding → UTF-8 (without BOM)

2. Rimuovi BOM Command line:
# 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

2. JSON Formatter (jsonformatter.org)
  • 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

Extensions:
  • 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:
  • ❌ Trailing commas
  • ❌ Single quotes
  • ❌ Chiavi senza quotes
  • ❌ Commenti
  • ❌ Parentesi non bilanciate
  • Strumenti essenziali:
    • JSONLint per validation
    • VS Code per editing
    • jq per command line
    • JSON.stringify per generazione

    Regola d'oro:

    Usa sempre JSON.stringify() per generare JSON, mai concatenazione manuale di stringhe!

    Share:

    Articoli Correlati

    Read in English