JSON Validation Guide: How to Validate and Fix JSON Errors
JSON Validation Guide: How to Validate and Fix JSON Errors
JSON (JavaScript Object Notation) is the most popular data format for APIs and configuration files. However, invalid JSON can break your applications. This guide will teach you how to validate and fix JSON errors effectively.
What is JSON Validation?
JSON validation ensures your data follows the correct JSON syntax rules. Valid JSON must:
- Use double quotes for strings (not single quotes)
- Have proper bracket matching
{}and[] - Separate items with commas
- Not have trailing commas
- Use valid data types (string, number, boolean, null, array, object)
Common JSON Errors
Error 1: Single Quotes Instead of Double Quotes
❌ Invalid:
{
'name': 'John',
'age': 30
}
✅ Valid:
{
"name": "John",
"age": 30
}
Error 2: Trailing Commas
❌ Invalid:
{
"name": "John",
"age": 30,
}
✅ Valid:
{
"name": "John",
"age": 30
}
Error 3: Unquoted Keys
❌ Invalid:
{
name: "John",
age: 30
}
✅ Valid:
{
"name": "John",
"age": 30
}
Error 4: Comments in JSON
❌ Invalid:
{
// This is a comment
"name": "John",
"age": 30
}
✅ Valid:
{
"name": "John",
"age": 30
}
Note: Standard JSON doesn’t support comments. Use JSON5 or JSONC if you need comments.
Error 5: Missing Commas
❌ Invalid:
{
"name": "John"
"age": 30
}
✅ Valid:
{
"name": "John",
"age": 30
}
How to Validate JSON
Method 1: Online JSON Validators
Use our Free JSON Validator to:
- ✅ Paste your JSON and validate instantly
- ✅ See exactly where errors occur
- ✅ Get helpful error messages
- ✅ Auto-format valid JSON
- ✅ No installation required
Method 2: JavaScript Validation
function validateJSON(jsonString) {
try {
JSON.parse(jsonString);
return { valid: true, error: null };
} catch (error) {
return {
valid: false,
error: error.message
};
}
}
// Usage
const result = validateJSON('{"name": "John"}');
if (result.valid) {
console.log('Valid JSON!');
} else {
console.log('Error:', result.error);
}
Method 3: Command Line
Using Node.js:
node -e "JSON.parse(require('fs').readFileSync('data.json', 'utf8'))"
Using jq (JSON processor):
jq . data.json
Using Python:
python -m json.tool data.json
JSON Schema Validation
For complex validation rules, use JSON Schema:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"age": {
"type": "number",
"minimum": 0,
"maximum": 150
},
"email": {
"type": "string",
"format": "email"
}
},
"required": ["name", "email"]
}
Validate against schema in JavaScript:
import Ajv from 'ajv';
const ajv = new Ajv();
const schema = { /* your schema */ };
const validate = ajv.compile(schema);
const data = {
"name": "John",
"age": 30,
"email": "[email protected]"
};
const valid = validate(data);
if (!valid) {
console.log(validate.errors);
}
Best Practices for JSON Validation
1. Validate at the Boundaries
Always validate JSON when:
- Receiving from external APIs
- Reading from files
- Accepting user input
- Before saving to database
2. Provide Helpful Error Messages
function validateUserJSON(jsonString) {
try {
const data = JSON.parse(jsonString);
if (!data.name) {
throw new Error('Missing required field: name');
}
if (typeof data.age !== 'number') {
throw new Error('Field "age" must be a number');
}
return { valid: true, data };
} catch (error) {
return {
valid: false,
error: error.message,
line: extractLineNumber(error)
};
}
}
3. Use TypeScript for Type Safety
interface User {
name: string;
age: number;
email: string;
}
function parseUser(jsonString: string): User {
const data = JSON.parse(jsonString);
// Runtime validation
if (!isValidUser(data)) {
throw new Error('Invalid user data');
}
return data as User;
}
function isValidUser(data: any): data is User {
return (
typeof data === 'object' &&
typeof data.name === 'string' &&
typeof data.age === 'number' &&
typeof data.email === 'string'
);
}
4. Handle Large JSON Files
For large files, use streaming parsers:
import { JSONParser } from '@streamparser/json';
const parser = new JSONParser();
parser.onValue = ({ value, key, parent, stack }) => {
// Process value
console.log(value);
};
// Stream data
stream.pipe(parser);
Common JSON Validation Tools
Browser DevTools
Chrome/Firefox DevTools automatically validate JSON:
- Open Network tab
- Click on API request
- View Response tab
- Invalid JSON will show error
VS Code Extensions
- JSON Tools - Format and validate
- JSON Schema Validator - Schema validation
- Prettier - Auto-format JSON
Online Tools
- DataFmt JSON Validator - Free, no signup
- JSONLint - Popular online validator
- JSON Formatter - Validate and beautify
Libraries
JavaScript:
ajv- JSON Schema validatorjoi- Data validationyup- Schema validation
Python:
jsonschema- JSON Schema validationpydantic- Data validation
PHP:
json-schema- Validation library- Native
json_decode()with error checking
Debugging JSON Errors
Finding the Error Line
function findJSONError(jsonString) {
try {
JSON.parse(jsonString);
return null;
} catch (error) {
const match = error.message.match(/position (\d+)/);
if (match) {
const position = parseInt(match[1]);
const lines = jsonString.substring(0, position).split('\n');
return {
line: lines.length,
column: lines[lines.length - 1].length,
message: error.message
};
}
return { message: error.message };
}
}
Visual Diff for JSON
Compare two JSON objects:
function compareJSON(json1, json2) {
const obj1 = JSON.parse(json1);
const obj2 = JSON.parse(json2);
const diff = {};
for (const key in obj1) {
if (obj1[key] !== obj2[key]) {
diff[key] = {
old: obj1[key],
new: obj2[key]
};
}
}
return diff;
}
API Response Validation
Fetch API with Validation
async function fetchJSON(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const contentType = response.headers.get('content-type');
if (!contentType?.includes('application/json')) {
throw new Error('Response is not JSON');
}
const data = await response.json();
return { success: true, data };
} catch (error) {
return {
success: false,
error: error.message
};
}
}
Axios with Validation
import axios from 'axios';
axios.interceptors.response.use(
response => {
// Validate response data structure
if (!isValidResponse(response.data)) {
return Promise.reject(new Error('Invalid response format'));
}
return response;
},
error => {
console.error('API Error:', error.message);
return Promise.reject(error);
}
);
Performance Tips
1. Cache Validation Results
const validationCache = new Map();
function validateWithCache(jsonString) {
const hash = hashString(jsonString);
if (validationCache.has(hash)) {
return validationCache.get(hash);
}
const result = validateJSON(jsonString);
validationCache.set(hash, result);
return result;
}
2. Lazy Validation
Only validate when needed:
class LazyJSON {
constructor(jsonString) {
this._raw = jsonString;
this._validated = false;
this._data = null;
}
get data() {
if (!this._validated) {
this._data = JSON.parse(this._raw);
this._validated = true;
}
return this._data;
}
}
Security Considerations
1. Prevent JSON Injection
// ❌ DANGEROUS
const userInput = req.body.input;
const json = `{"data": "${userInput}"}`;
JSON.parse(json); // Vulnerable!
// ✅ SAFE
const data = {
data: userInput
};
const json = JSON.stringify(data);
2. Validate Size Limits
function validateJSONSize(jsonString, maxBytes = 1000000) {
const size = new Blob([jsonString]).size;
if (size > maxBytes) {
throw new Error(`JSON too large: ${size} bytes`);
}
return JSON.parse(jsonString);
}
3. Sanitize Before Display
function sanitizeJSON(obj) {
return JSON.parse(JSON.stringify(obj, (key, value) => {
if (typeof value === 'string') {
return value.replace(/</g, '<').replace(/>/g, '>');
}
return value;
}));
}
Try Our JSON Validator
Ready to validate your JSON? Use our Free JSON Validator & Formatter:
- 🔍 Instant validation with line numbers
- ✨ Auto-formatting for valid JSON
- 🎯 Clear error messages
- 🚀 No installation needed
- 🔒 100% client-side (private)
- 💯 Free forever
Summary
Key Takeaways:
- Always validate JSON from external sources
- Use try-catch for JSON.parse()
- Provide clear error messages
- Consider JSON Schema for complex validation
- Validate at API boundaries
- Use proper tools and libraries
- Don’t forget security considerations
Common Mistakes to Avoid:
- ❌ Trusting external JSON without validation
- ❌ Ignoring parse errors
- ❌ Using single quotes
- ❌ Adding trailing commas
- ❌ Forgetting to validate data types
Need to validate JSON quickly? Try our free JSON validator tool!
Found this helpful? Try our free tools!
Explore Our Tools →