Common JSON Syntax Errors
Here are the most common JSON errors and how to fix them:
1. Trailing Commas
1// ❌ Invalid2{"name": "John", "age": 30,}34// ✅ Valid5{"name": "John", "age": 30}
2. Single Quotes
1// ❌ Invalid2{'name': 'John'}34// ✅ Valid5{"name": "John"}
3. Unquoted Keys
1// ❌ Invalid2{name: "John"}34// ✅ Valid5{"name": "John"}
4. Comments
1// ❌ Invalid - JSON doesn't support comments2{3 "name": "John" // This breaks4}56// ✅ Valid - Use a field for notes7{8 "_comment": "User data",9 "name": "John"10}
5. Unescaped Special Characters
1// ❌ Invalid2{"path": "C:\Users\John"}34// ✅ Valid5{"path": "C:\\Users\\John"}
Validate JSON in JavaScript
Use try-catch with JSON.parse() to validate JSON:
// Basic validation
function isValidJson(str) {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
}
// Validation with error details
function validateJson(str) {
try {
const parsed = JSON.parse(str);
return { valid: true, data: parsed };
} catch (e) {
return {
valid: false,
error: e.message,
// Extract position from error message
position: e.message.match(/position (\d+)/)?.[1]
};
}
}
// Usage
const result = validateJson('{"name": "John",}');
if (!result.valid) {
console.error('Invalid JSON:', result.error);
// "Invalid JSON: Unexpected token } in JSON at position 16"
}
// Validate and format in one step
function validateAndFormat(str) {
const parsed = JSON.parse(str); // Throws if invalid
return JSON.stringify(parsed, null, 2);
}Validate JSON in Python
Python's json module raises JSONDecodeError for invalid JSON:
import json
def is_valid_json(s):
try:
json.loads(s)
return True
except json.JSONDecodeError:
return False
def validate_json(s):
try:
data = json.loads(s)
return {"valid": True, "data": data}
except json.JSONDecodeError as e:
return {
"valid": False,
"error": str(e),
"line": e.lineno,
"column": e.colno,
"position": e.pos
}
# Usage
result = validate_json('{"name": "John",}')
if not result["valid"]:
print(f"Error at line {result['line']}, column {result['column']}")
print(f"Message: {result['error']}")
# Validate JSON file
def validate_json_file(filepath):
try:
with open(filepath, 'r') as f:
json.load(f)
return True
except (json.JSONDecodeError, FileNotFoundError) as e:
print(f"Error: {e}")
return FalseValidate JSON in Java
Use Jackson or Gson to validate JSON in Java:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
public class JsonValidator {
private static final ObjectMapper mapper = new ObjectMapper();
public static boolean isValidJson(String json) {
try {
mapper.readTree(json);
return true;
} catch (Exception e) {
return false;
}
}
public static ValidationResult validateJson(String json) {
try {
JsonNode node = mapper.readTree(json);
return new ValidationResult(true, node, null);
} catch (Exception e) {
return new ValidationResult(false, null, e.getMessage());
}
}
public static void main(String[] args) {
String json = "{\"name\": \"John\",}"; // Invalid - trailing comma
ValidationResult result = validateJson(json);
if (!result.isValid()) {
System.out.println("Invalid JSON: " + result.getError());
}
}
}JSON Schema Validation
For complex validation beyond syntax, use JSON Schema:
// Using Ajv (npm install ajv)
const Ajv = require('ajv');
const ajv = new Ajv();
// Define a schema
const schema = {
type: "object",
properties: {
name: { type: "string", minLength: 1 },
age: { type: "integer", minimum: 0 },
email: { type: "string", format: "email" }
},
required: ["name", "email"],
additionalProperties: false
};
// Compile and validate
const validate = ajv.compile(schema);
const data = { name: "John", age: 30, email: "john@example.com" };
const valid = validate(data);
if (!valid) {
console.log("Validation errors:", validate.errors);
}
// Python equivalent using jsonschema
// pip install jsonschema
/*
from jsonschema import validate, ValidationError
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer", "minimum": 0}
},
"required": ["name"]
}
try:
validate(instance={"name": "John", "age": 30}, schema=schema)
except ValidationError as e:
print(f"Validation error: {e.message}")
*/Frequently Asked Questions
Why is my JSON invalid?
The most common causes are: trailing commas, single quotes instead of double quotes, unquoted keys, comments, and unescaped special characters in strings.
How do I find the error position in JSON?
Most parsers report the character position or line/column number where parsing failed. Our JSON Validator tool highlights the exact error location.
What's the difference between syntax and schema validation?
Syntax validation checks if JSON is well-formed. Schema validation checks if the data matches expected types, required fields, and constraints.
Can I validate JSON against a TypeScript interface?
Not directly at runtime. Use libraries like Zod, io-ts, or generate JSON Schema from TypeScript types.