How to Validate JSON — Syntax Checking, Schema Validation & Error Fixes
Validating JSON means two different things: checking that the syntax is correct (the JSON can be parsed), and checking that the structure matches what your application expects (the right fields, types, and required values are present). This guide covers both — syntax validation with exact error messages, schema validation with JSON Schema drafts, and how to fix the most common JSON validation failures.
Syntax
Is this valid JSON? — quotes, brackets, commas, no comments
Schema
Does this JSON have the right fields and types? — JSON Schema validation
Line:col
Exact error position — not just "invalid JSON", but where and why
Two Types of JSON Validation — Syntax vs. Schema
Most developers think of JSON validation as syntax checking. But in production systems, schema validation is equally important — it catches valid-syntax JSON that still breaks your application because a required field is missing or a value has the wrong type.
Syntax validation
Checks that the JSON string is parseable — correct use of quotes, brackets, commas, and no forbidden characters like comments. A syntax error means JSON.parse() will throw. All major programming languages have built-in JSON parsers that do this.
Schema validation
Checks that the parsed JSON conforms to an expected structure — required fields present, values have the right types, strings match patterns, numbers are in range. JSON Schema (Draft 4–2020-12) is the standard format for defining these constraints.
When syntax validation is enough
For ad-hoc debugging, quick checks before committing a JSON config file, and formatting tools that need to parse before pretty-printing. Most developer tools and online formatters do syntax validation.
When schema validation is required
For API request validation (reject invalid payloads before processing), CI pipeline checks (config files match expected schema), and data pipeline validation (incoming records have all required fields with correct types).
Syntax Validation — Is This Valid JSON?
The JSON specification (RFC 8259) is strict: double-quoted strings, no trailing commas, no comments, no undefined, no single quotes. Any deviation is a syntax error.
// Built-in: JSON.parse() throws SyntaxError for invalid JSON
function isValidJson(str) {
try {
JSON.parse(str);
return true;
} catch {
return false;
}
}
// Better: get the error message with position
function validateJson(str) {
try {
const parsed = JSON.parse(str);
return { valid: true, data: parsed };
} catch (e) {
return {
valid: false,
error: e.message, // e.g. "Unexpected token , in JSON at position 45"
};
}
}
// Usage
const result = validateJson('{"name": "Alice",}');
// { valid: false, error: "Unexpected token } in JSON at position 18" }import json
def validate_json(json_string: str) -> dict:
try:
data = json.loads(json_string)
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,
}
result = validate_json('{"name": "Alice",}')
# {'valid': False, 'error': 'Trailing comma...', 'line': 1, 'column': 18}Validate without writing code
Schema Validation — Does the JSON Have the Right Structure?
JSON Schema defines the expected shape of JSON data. It specifies required fields, value types, string patterns, number ranges, and array constraints. A validator checks your JSON against the schema and reports every mismatch.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["id", "name", "email", "role"],
"properties": {
"id": {
"type": "integer",
"minimum": 1
},
"name": {
"type": "string",
"minLength": 2,
"maxLength": 100
},
"email": {
"type": "string",
"format": "email"
},
"role": {
"type": "string",
"enum": ["admin", "editor", "viewer", "guest"]
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 150
}
},
"additionalProperties": false
}{
"id": 42,
"name": "Alice Smith",
"email": "alice@example.com",
"role": "admin"
}
// ✓ All required fields present
// ✓ id is integer ≥ 1
// ✓ name is string 2–100 chars
// ✓ email matches email format
// ✓ role is one of allowed enum values{
"id": "forty-two",
"name": "A",
"email": "not-an-email",
"role": "superuser",
"unexpectedField": true
}
// ✗ id: must be integer (got string)
// ✗ name: must be at least 2 characters (got 1)
// ✗ email: must match email format
// ✗ role: must be one of ["admin","editor","viewer","guest"]
// ✗ unexpectedField: additional properties not allowedValidate JSON in Code — Express, Fastify, Python
import Ajv from 'ajv';
import addFormats from 'ajv-formats'; // for email, uri, date-time formats
const ajv = new Ajv({ allErrors: true }); // allErrors: report ALL errors, not just first
addFormats(ajv);
const userSchema = {
type: 'object',
required: ['id', 'name', 'email', 'role'],
properties: {
id: { type: 'integer', minimum: 1 },
name: { type: 'string', minLength: 2, maxLength: 100 },
email: { type: 'string', format: 'email' },
role: { type: 'string', enum: ['admin', 'editor', 'viewer', 'guest'] },
},
additionalProperties: false,
};
const validate = ajv.compile(userSchema);
// In an Express route
app.post('/users', (req, res) => {
const valid = validate(req.body);
if (!valid) {
return res.status(400).json({
error: 'Validation failed',
details: validate.errors, // array of all validation errors
});
}
// proceed with valid data
createUser(req.body);
});import json
import jsonschema
from jsonschema import validate, ValidationError
schema = {
"type": "object",
"required": ["id", "name", "email"],
"properties": {
"id": {"type": "integer", "minimum": 1},
"name": {"type": "string", "minLength": 2},
"email": {"type": "string", "format": "email"},
}
}
def validate_user(data: dict) -> list[str]:
validator = jsonschema.Draft202012Validator(schema)
errors = list(validator.iter_errors(data))
return [e.message for e in errors]
# Usage
user = {"id": "not-an-int", "name": "A", "email": "bad-email"}
errors = validate_user(user)
# [''not-an-int' is not of type 'integer'',
# ''A' is too short',
# ''bad-email' is not a 'email'']Common JSON Validation Errors and How to Fix Them
Required field missing
Missing required fields — API returns 400
// Schema requires: id, name, email, role
// Submitted JSON:
{
"id": 42,
"name": "Alice"
// email and role are missing
}
// Validation error: required fields 'email', 'role' are missingAll required fields present — validation passes
// All required fields present
{
"id": 42,
"name": "Alice Smith",
"email": "alice@example.com",
"role": "editor"
}Wrong type — string sent where integer expected
String "42" fails integer type check
// Schema: { "id": { "type": "integer" } }
// Common when reading from form inputs or URL params:
{
"id": "42", ← string "42", not integer 42
"name": "Alice"
}
// Validation error: /id must be integerInteger 42 — no quotes, passes integer validation
// Parse/cast before sending to API
const id = parseInt(formData.get('id'), 10);
const payload = { id, name: formData.get('name') };
// Or in the JSON:
{
"id": 42, ← integer 42, no quotes
"name": "Alice"
}Validate JSON Online — Without Writing Code
Paste your JSON into the validator
Go to unblockdevs.com/json-validator. Paste the JSON you want to validate in the left panel. Syntax errors appear immediately with line and column numbers.
Add a JSON Schema (optional)
Paste your JSON Schema in the right panel. The validator checks the JSON against the schema and lists every mismatch — missing required fields, wrong types, enum violations, and additional properties.
Read the error report
Each error shows the JSON path (e.g., /user/email), the constraint that failed, and the actual value. Use these to fix the JSON or update the schema.
Test different JSON Schema drafts
The validator supports Draft 4, 6, 7, 2019-09, and 2020-12. Select the draft your schema targets — different drafts support different keywords ($defs vs definitions, unevaluatedProperties, etc.).