JSON Formatting and Validation: Common Errors and How to Fix Them
"Unexpected token in JSON" is one of the most common errors developers hit — and one of the most frustrating because the error message rarely points at the actual problem clearly. This guide covers the most common JSON syntax errors, how to find and fix them, and how to validate JSON properly before it causes a production bug.
The Most Common JSON Syntax Errors
1. Trailing Commas
JSON does not allow trailing commas — unlike JavaScript object literals.
// ❌ Invalid — trailing comma after last property
{
"name": "Ayesha",
"email": "ayesha@example.com",
}
// ✅ Valid
{
"name": "Ayesha",
"email": "ayesha@example.com"
}2. Single Quotes Instead of Double Quotes
JSON requires double quotes for strings and keys. Single quotes are invalid.
// ❌ Invalid
{ 'name': 'Ayesha' }
// ✅ Valid
{ "name": "Ayesha" }3. Unquoted Keys
// ❌ Invalid — JavaScript object syntax, not JSON
{ name: "Ayesha", email: "ayesha@example.com" }
// ✅ Valid
{ "name": "Ayesha", "email": "ayesha@example.com" }4. Unescaped Special Characters in Strings
// ❌ Invalid — unescaped quote breaks the string
{ "quote": "She said "hello" to me" }
// ✅ Valid — escape internal double quotes
{ "quote": "She said \"hello\" to me" }
// Other characters that need escaping:
// \\ backslash \n newline
// \t tab \r carriage return
// \/ forward slash (optional but common)5. NaN, undefined, and Infinity
These are valid JavaScript values but invalid JSON. JSON only supports: string, number, boolean, null, object, array.
// ❌ Invalid
{ "score": NaN, "limit": undefined, "max": Infinity }
// ✅ Valid — use null or a string representation
{ "score": null, "limit": null, "max": null }6. Comments
JSON does not support comments at all — neither // nor /* */.
// ❌ Invalid
{
// this is the user's name
"name": "Ayesha"
}
// ✅ Valid — remove comments, or use a separate "_comment" field if needed
{
"name": "Ayesha"
}7. Leading Zeros in Numbers
// ❌ Invalid — leading zero not allowed
{ "zipCode": 07001 }
// ✅ Valid — quote it as a string instead
{ "zipCode": "07001" }Debugging "Unexpected Token" Errors
When you see an error like:
SyntaxError: Unexpected token } in JSON at position 142The position number tells you the character offset where parsing failed. Find it programmatically:
const jsonString = '...'; // your problematic JSON
const position = 142;
console.log(jsonString.slice(Math.max(0, position - 30), position + 30));
// Shows 30 characters before and after the error — usually enough to spot the issueCommon cause-to-symptom mapping:
| Error Message | Likely Cause |
|---|---|
| Unexpected token } | Trailing comma before closing brace |
| Unexpected token in JSON at position 0 | Empty string, or response wasn't JSON at all (often HTML error page) |
| Unexpected end of JSON input | JSON was truncated — missing closing brace/bracket |
| Unexpected string | Missing comma between two properties |
Validating JSON Programmatically
Quick Validity Check (JavaScript)
function isValidJSON(str) {
try {
JSON.parse(str);
return true;
} catch {
return false;
}
}Schema Validation with Zod (TypeScript)
Valid JSON syntax doesn't mean the data has the shape you expect. Use a schema validator for structural checks:
import { z } from 'zod';
const UserSchema = z.object({
id: z.string().uuid(),
fullName: z.string().min(1),
email: z.string().email(),
status: z.enum(['active', 'inactive', 'pending']),
});
const result = UserSchema.safeParse(parsedJson);
if (!result.success) {
console.error(result.error.issues);
}JSON Schema Validation (Python)
import jsonschema
schema = {
"type": "object",
"properties": {
"id": {"type": "string"},
"email": {"type": "string", "format": "email"},
"status": {"enum": ["active", "inactive", "pending"]},
},
"required": ["id", "email", "status"],
}
try:
jsonschema.validate(instance=data, schema=schema)
except jsonschema.ValidationError as e:
print(f"Validation error: {e.message}")Avoiding JSON Errors Entirely
The best way to avoid hand-written JSON syntax errors is to not hand-write JSON at all. When you need test data or example payloads:
- Generate it with Dummy JSON Generator — output is always syntactically valid by construction
- Use
JSON.stringify()in JavaScript instead of typing JSON by hand - Validate any JSON you do write by hand with a linter or your editor's built-in JSON validation (VS Code highlights JSON errors automatically)
- Use a schema (Zod, JSON Schema, Pydantic) at the application boundary so malformed data fails fast with a clear error instead of causing subtle bugs downstream
Need valid, well-formatted test JSON without the syntax headaches? Generate it here — guaranteed valid JSON, every time.