·5 min read
JSON Error Handling Best Practices: Robust Error Management
JSON error handling is a critical skill for every developer. Whether parsing user input, processing API responses, or reading configuration files, JSON operations can fail in many ways. Robust error handling distinguishes production-grade code from prototypes. This guide covers JSON parsing errors, validation strategies, graceful degradation, retry patterns, and error reporting across multiple languages. Use our JSON Validator to find syntax errors quickly and JSON Fixer to repair common issues.
Common JSON Error Types
| Error Type | Example | Typical Message |
|---|---|---|
| Syntax error | Trailing comma, missing quote | Unexpected token , in JSON at position 42 |
| Type mismatch | Expected number, got string | Expected type 'number' but got 'string' |
| Unexpected token | Single quotes instead of double | Unexpected token ' in JSON at position 5 |
| Unexpected end of input | Truncated JSON | Unexpected end of JSON input |
| Circular reference | Object references itself | Converting circular structure to JSON |
| Value out of range | Number exceeds precision | Silent precision loss (no error thrown) |
| Duplicate keys | Same key appears twice | Last value wins (no error in most parsers) |
JSON.parse Error Handling by Language
JavaScript
function safeJSONParse(str) {
try {
const data = JSON.parse(str);
return { success: true, data, error: null };
} catch (error) {
if (error instanceof SyntaxError) {
// Extract position
const posMatch = error.message.match(/positions+(d+)/);
const position = posMatch ? parseInt(posMatch[1]) : -1;
// Show context
const contextStart = Math.max(0, position - 15);
const contextEnd = Math.min(str.length, position + 15);
return {
success: false,
data: null,
error: {
message: error.message,
position,
context: str.substring(contextStart, contextEnd),
pointer: ' '.repeat(Math.min(15, position)) + '^--- here'
}
};
}
throw error; // Re-throw non-JSON errors
}
}
const result = safeJSONParse(userInput);
if (!result.success) {
console.error('JSON parse error:');
console.error(' Message:', result.error.message);
console.error(' Context:', result.error.context);
console.error(' Pointer:', result.error.pointer);
}
Python
import json
def safe_json_loads(json_string):
try:
data = json.loads(json_string)
return {"success": True, "data": data, "error": None}
except json.JSONDecodeError as e:
return {
"success": False,
"data": None,
"error": {
"message": str(e),
"position": e.pos,
"line": e.lineno,
"column": e.colno
}
}
Go
import "encoding/json"
type SafeResult struct {
Data interface{}
Error *JSONParseError
}
type JSONParseError struct {
Message string
Offset int64
}
func safeUnmarshal(data []byte) SafeResult {
var result interface{}
err := json.Unmarshal(data, &result)
if err != nil {
return SafeResult{
Error: &JSONParseError{
Message: err.Error(),
Offset: findErrorOffset(data, err),
},
}
}
return SafeResult{Data: result}
}
Graceful Degradation Strategies
// Fallback to default values on parse failure
function parseWithDefaults(jsonStr, defaults = {}) {
try {
return { ...defaults, ...JSON.parse(jsonStr) };
} catch {
return defaults;
}
}
// Partial parsing (extract what you can)
function partialParse(jsonStr) {
const result = {};
try {
const data = JSON.parse(jsonStr);
// Extract known fields, ignore unknown
const knownFields = ['name', 'email', 'age'];
for (const field of knownFields) {
if (field in data) {
result[field] = data[field];
}
}
} catch {
// Return whatever we have
}
return result;
}
API Error Response Format
// Consistent JSON error format for APIs
{
"error": {
"code": "INVALID_JSON",
"message": "The request body contains invalid JSON",
"details": {
"position": 42,
"context": "...data: "unfinished",
"suggestion": "Check for missing closing quote at position 42"
},
"requestId": "req_abc123",
"timestamp": "2025-01-15T10:30:00Z"
}
}
// HTTP status codes for JSON errors
// 400 - Malformed JSON request body
// 413 - JSON payload too large
// 415 - Unsupported content type
// 422 - Valid JSON but semantic validation failed
// 500 - Internal JSON processing error
Error Prevention Best Practices
- Validate JSON before parsing with JSON Validator
- Fix common errors automatically with JSON Fixer
- Use
try/catcharound everyJSON.parse()call without exception - Log the full error context, not just the message
- Implement exponential backoff for retryable JSON operations
- Set maximum payload size limits (e.g., 1MB) to prevent OOM errors
- Monitor JSON parse error rates in production
Next Steps
Validate JSON before processing with JSON Validator. Fix common errors with JSON Fixer. Format error outputs with JSON Formatter.