JSON Syntax Error: How to Find and Fix It
A JSON syntax error means the parser encountered a character or token that violates the formal grammar rules of the JSON specification (RFC 8259). Unlike application-level logic errors, syntax errors prevent the entire JSON document from being parsed. This comprehensive guide covers every type of JSON syntax error across multiple programming languages with practical debugging strategies. Use our JSON Syntax Checker for instant validation.
Understanding the JSON Grammar
JSON's grammar is defined by a strict set of production rules. A JSON document must be either an object {}, an array [], or a literal value (string, number, boolean, null). The grammar does not allow comments, trailing commas, single quotes, unquoted keys, or hexadecimal numbers. Every violation produces a syntax error at a specific position in the input. Our JSON Validator pinpoints errors to the exact line and column with clear messages.
Complete Taxonomy of JSON Syntax Errors
| Error Type | Invalid Input | Parser Message | Fix |
|---|---|---|---|
| Trailing comma | {"a":1,} | Expected '}' got ',' | Remove comma after last element |
| Unquoted key | {name: "Alice"} | Expected '"' got 'n' | Wrap key in double quotes |
| Single-quoted string | {'key': 'val'} | Expected '"' got "'" | Replace with double quotes |
| Missing comma | {"a":1 "b":2} | Expected ',' got '"' | Add comma between values |
| Extra comma in array | [1,,2] | Expected value got ',' | Remove duplicate comma |
| Leading zero | {"n": 01} | Expected digit got '1' | Remove leading zero |
| Mismatched bracket | {"a":[1,2] | Expected '}' got EOF | Add missing closing brace |
| Invalid escape | "hello\x" | Bad escape character | Use valid escape: \n, \t, \", \\ |
Parser Error Messages Across Languages
JavaScript (V8 Engine)
try {
JSON.parse('{"name": "Alice",}');
} catch (e) {
// SyntaxError: Expected double-quoted property name at position 19
console.log(e.message);
const pos = parseInt(e.message.match(/position (d+)/)[1]);
console.log("Error near:", jsonString.substring(Math.max(0,pos-5), pos+5));
}
Python
import json
try:
data = json.loads('{"name": "Alice",}')
except json.JSONDecodeError as e:
print(f"Line {e.lineno}, Col {e.colno}: {e.msg}")
print(f"Char {e.pos}: ...{e.doc[max(0,e.pos-10):e.pos+10]}...")
Java (Jackson)
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode node = mapper.readTree(jsonString);
} catch (JsonProcessingException e) {
JsonLocation loc = e.getLocation();
System.err.printf("Error at line %d, column %d: %s%n",
loc.getLineNr(), loc.getColumnNr(), e.getMessage());
}
Go
import "encoding/json"
var data map[string]interface{}
err := json.Unmarshal([]byte(jsonString), &data)
if syntaxErr, ok := err.(*json.SyntaxError); ok {
log.Printf("Syntax error at offset %d: %s",
syntaxErr.Offset, syntaxErr.Error())
}
Step-by-Step Debugging Strategy
- Isolate the error — Paste your JSON into our JSON Syntax Checker for immediate diagnosis
- Read the error position — Note the line, column, and character offset. Most parsers include this information
- Inspect the context — Look at 10-20 characters before and after the reported position. The actual mistake is often just before the reported location
- Check common culprits — Missing quotes, trailing commas, and mismatched brackets account for 80% of syntax errors
- Use automated repair — Our JSON Repair can fix many common errors automatically
- Validate with schema — Use JSON Schema Validator for structural correctness
Commonly Overlooked Syntax Errors
- BOM characters — UTF-8 BOM at the start of a file causes baffling "Unexpected token" errors. Strip BOM before parsing
- Zero-width characters — Invisible Unicode characters (zero-width space U+200B) pasted from web pages break parsing silently
- Control characters — ASCII control codes (0x00-0x1F) except tab are not allowed in JSON strings without escaping
- Deep nesting — Some parsers limit nesting depth (typically 512-1024 levels). Use JSON Depth Analyzer to check
Preventing Syntax Errors in Production
- Use a code editor with real-time JSON validation (VS Code, WebStorm)
- Add JSON syntax checking to your CI/CD pipeline with pre-commit hooks
- Enable format-on-save to catch errors immediately
- Use JSON Schema for structural validation in addition to syntax checking
- For API responses, always validate the response format before parsing
Edge Cases and Advanced Scenarios
Empty arrays [] and empty objects {} are valid JSON at any nesting level. The empty string "" is valid JSON representing an empty string value, while a completely empty input (zero characters) is invalid. The number -0 is valid JSON and equals 0 in most languages. Very large numbers may lose precision when parsed — consider using strings for numbers exceeding 53 bits in JavaScript. Whitespace is allowed between tokens but not within tokens: nu ll is invalid while null is valid.
Next Steps
Check your JSON now with our free JSON Syntax Checker. For recurring validation, keep our JSON Validator and JSON Repair bookmarked.