UnblockDevs

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

1

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).

2

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.

javascriptSyntax validation in JavaScript
// 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" }
pythonSyntax validation in Python
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

Paste any JSON into the JSON Validator at unblockdevs.com/json-validator — it shows the exact line and column of every error, auto-highlights the problem in the editor, and suggests the fix. Works for syntax validation and JSON Schema validation in one tool.
3

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.

jsonJSON Schema example — user object validation
{
  "$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
}
jsonValid JSON — passes all schema checks
{
  "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
jsonInvalid JSON — schema validation errors
{
  "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 allowed
4

Validate JSON in Code — Express, Fastify, Python

javascriptJSON Schema validation with AJV in Node.js
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);
});
pythonJSON Schema validation with jsonschema in Python
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'']
5

Common JSON Validation Errors and How to Fix Them

Required field missing

Missing required fields — API returns 400

❌ Bad
// Schema requires: id, name, email, role
// Submitted JSON:
{
  "id": 42,
  "name": "Alice"
  // email and role are missing
}
// Validation error: required fields 'email', 'role' are missing

All required fields present — validation passes

✅ Good
// 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

❌ Bad
// 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 integer

Integer 42 — no quotes, passes integer validation

✅ Good
// 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"
}
6

Validate JSON Online — Without Writing Code

1

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.

2

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.

3

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.

4

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.).

Frequently Asked Questions