JSON Validation Guide: Ensure Your Data is Correct
Validating JSON is a critical step in any development workflow. Invalid JSON can cause application crashes, data corruption, and security vulnerabilities. This guide covers everything you need to know about JSON validation.
Why Validate JSON?
JSON validation ensures that your data conforms to the expected structure and syntax. Without proper validation, you risk:
- Runtime errors: Invalid JSON will cause parsing failures in your application
- Data corruption: Malformed data can lead to incorrect database entries
- Security issues: Unvalidated input is a common attack vector
- Debugging nightmares: Tracking down subtle JSON errors wastes valuable time
Two Levels of JSON Validation
1. Syntax Validation
Syntax validation checks whether a string is valid JSON according to the JSON specification (RFC 8259). This is the most basic level of validation.
Valid JSON
{
"name": "John Doe",
"age": 30,
"isActive": true
}
Invalid JSON — Common Syntax Errors
// Trailing comma (INVALID)
{
"name": "John",
"age": 30,
}
// Single quotes (INVALID)
{
'name': 'John'
}
// Unquoted keys (INVALID)
{
name: "John"
}
// Comments (INVALID in standard JSON)
{
"name": "John" // This is not allowed
}
2. Schema Validation
Schema validation goes beyond syntax to verify that the JSON data matches an expected structure, including data types, required fields, value constraints, and more.
JSON Schema
JSON Schema is a powerful vocabulary for annotating and validating JSON documents. It allows you to define the structure, constraints, and documentation of your JSON data.
Basic Schema Example
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "User",
"description": "A user object",
"type": "object",
"required": ["name", "email", "age"],
"properties": {
"name": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"email": {
"type": "string",
"format": "email"
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 150
},
"roles": {
"type": "array",
"items": {
"type": "string",
"enum": ["admin", "user", "editor"]
},
"uniqueItems": true
}
},
"additionalProperties": false
}
Advertisement
Schema Validation Keywords
| Keyword | Applies To | Description |
|---|---|---|
type | Any | Specifies the data type (string, number, object, array, boolean, null) |
required | Object | Lists fields that must be present |
properties | Object | Defines the schema for each property |
minLength / maxLength | String | String length constraints |
minimum / maximum | Number | Numeric value constraints |
enum | Any | Restricts value to a predefined set |
pattern | String | Regex pattern the string must match |
items | Array | Schema for array elements |
minItems / maxItems | Array | Array length constraints |
uniqueItems | Array | Ensures all array items are unique |
additionalProperties | Object | Controls whether extra properties are allowed |
Validation in Different Languages
JavaScript
// Basic syntax validation
function isValidJSON(str) {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
}
// Schema validation with Ajv
const Ajv = require('ajv');
const ajv = new Ajv();
const validate = ajv.compile(schema);
const valid = validate(data);
if (!valid) console.log(validate.errors);
Python
import json
from jsonschema import validate, ValidationError
# Syntax validation
try:
data = json.loads(json_string)
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e}")
# Schema validation
try:
validate(instance=data, schema=schema)
except ValidationError as e:
print(f"Validation error: {e.message}")
PHP
// Syntax validation
$data = json_decode($jsonString);
if (json_last_error() !== JSON_ERROR_NONE) {
echo "Invalid JSON: " . json_last_error_msg();
}
Online Validation Tools
- JSON Beautifier Pro — Our tool validates JSON instantly with detailed error messages
- JSONLint — A popular online JSON validator
- JSON Schema Validator — Validates JSON against a schema
Validation Best Practices
- Validate early: Check JSON at the entry point of your application (API endpoints, file uploads)
- Use schemas: Define JSON Schema for all your API contracts
- Provide clear errors: Return helpful error messages that indicate what went wrong and where
- Validate on both sides: Validate on the client for UX, and on the server for security
- Automate validation: Include schema validation in your CI/CD pipeline