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:

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
typeAnySpecifies the data type (string, number, object, array, boolean, null)
requiredObjectLists fields that must be present
propertiesObjectDefines the schema for each property
minLength / maxLengthStringString length constraints
minimum / maximumNumberNumeric value constraints
enumAnyRestricts value to a predefined set
patternStringRegex pattern the string must match
itemsArraySchema for array elements
minItems / maxItemsArrayArray length constraints
uniqueItemsArrayEnsures all array items are unique
additionalPropertiesObjectControls 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

Validation Best Practices

  1. Validate early: Check JSON at the entry point of your application (API endpoints, file uploads)
  2. Use schemas: Define JSON Schema for all your API contracts
  3. Provide clear errors: Return helpful error messages that indicate what went wrong and where
  4. Validate on both sides: Validate on the client for UX, and on the server for security
  5. Automate validation: Include schema validation in your CI/CD pipeline
Need to validate your JSON? Try our free JSON Beautifier & Validator now!