JSON Schema Validator
Validate JSON data instances against formal JSON Schema Draft-07 specifications with granular path error diagnostics.
Unlike conventional calculator sites that send your financial numbers, payload data, or code snippets across remote web servers, Affi-Chain processes all mathematical derivations, algorithms, and data parsing 100% locally within your browser sandbox. No tracking cookies, no server-side retention, and zero transmission lag.
What is JSON Schema Validation?
JSON Schema Validation evaluates a JSON data document against a formal contract specification defined by the IETF JSON Schema specification (Draft-07, Draft 2019-09, and Draft 2020-12). In modern microservice architectures, cloud infrastructure pipelines, and REST API development, JSON is the default serialization medium for exchanging data.
However, JSON itself is inherently schema-less; it does not enforce required keys, numeric bounds, or string formatting. Without validation at API gateways and service boundaries, corrupted or malicious payloads penetrate application memory, causing runtime exceptions, data corruption, and security vulnerabilities like SQL injection or mass-assignment bugs.
JSON Schema provides a declarative, JSON-based format to define the precise structure, types, constraints, and relationships of valid payloads. It forms the foundational schema definition language powering OpenAPI 3.1, Swagger, AsyncAPI, and modern database validation layers.
The Affi-Chain JSON Schema Validator provides real-time, 100% in-browser contract testing powered by high-performance schema engines, highlighting syntax discrepancies, missing properties, and constraint violations instantly with zero server round-trips.
Core JSON Schema Validation Keywords Matrix
JSON Schema specifications structure constraints through declarative property keywords:
| Keyword Category | Keyword | Constraint Behavior | Architectural Example |
|---|---|---|---|
| Type Assertion | type | Enforces primitive or composite types | "type": ["string", "null"] |
| Object Properties | required | Array of keys that must exist in instance | "required": ["id", "email"] |
| Strict Objects | additionalProperties | Forbids undeclared extraneous fields | "additionalProperties": false |
| Numeric Boundaries | minimum / maximum | Enforces inclusive numerical ranges | "minimum": 0, "maximum": 100 |
| Exclusive Numeric | exclusiveMinimum | Value must be strictly greater than ($>$) | "exclusiveMinimum": 0 |
| String Constraints | minLength / maxLength | Sets character length boundaries | "minLength": 8, "maxLength": 128 |
| Pattern Matching | pattern | Enforces ECMA-262 regular expressions | "pattern": "^[A-Z]{3}-[0-9]{4}$" |
| Semantic Format | format | Validates standard internet formats | "format": "date-time" or "email" |
| Array Sizing | minItems / maxItems | Restricts element counts in lists | "minItems": 1, "uniqueItems": true |
| Logical Unions | anyOf / oneOf | Validates against multiple conditional schemas | "oneOf": [{"$ref": "#/$defs/A"}, ...] |
| Reusability | $defs and $ref | Defines reusable sub-schemas across types | "$ref": "#/$defs/Address" |
Step-by-Step Practical Transformation Example
Let us examine a production JSON Schema contract designed to validate an enterprise SaaS user creation payload:
The JSON Schema Specification (user-contract.json):
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "CreateUserRequest",
"type": "object",
"required": ["username", "email", "age", "roles"],
"additionalProperties": false,
"properties": {
"username": {
"type": "string",
"minLength": 3,
"maxLength": 30,
"pattern": "^[a-z0-9_-]+$"
},
"email": {
"type": "string",
"format": "email"
},
"age": {
"type": "integer",
"minimum": 18,
"maximum": 120
},
"roles": {
"type": "array",
"minItems": 1,
"uniqueItems": true,
"items": {
"type": "string",
"enum": ["member", "billing_admin", "super_admin"]
}
},
"billingAddress": {
"$ref": "#/$defs/Address"
}
},
"$defs": {
"Address": {
"type": "object",
"required": ["street", "city", "country"],
"properties": {
"street": { "type": "string" },
"city": { "type": "string" },
"country": { "type": "string", "minLength": 2, "maxLength": 2 }
}
}
}
}
Valid Payload Instance:
{
"username": "alex_dev",
"email": "alex.dev@example.com",
"age": 28,
"roles": ["member", "billing_admin"]
}
Practical Code Implementation: Programmatic Validation Suites
1. Modern JavaScript / Node.js via Ajv (Another JSON Schema Validator)
Ajv is the industry-standard JSON Schema engine compiled to optimized JavaScript:
import Ajv from "ajv";
import addFormats from "ajv-formats";
const ajv = new Ajv({ allErrors: true, strict: true });
addFormats(ajv); // Adds email, uri, date-time format validators
const schema = {
type: "object",
properties: {
sku: { type: "string", pattern: "^[A-Z]{3}-[0-9]+$" },
price: { type: "number", minimum: 0.01 }
},
required: ["sku", "price"],
additionalProperties: false
};
const validate = ajv.compile(schema);
const testPayload = { sku: "PRD-1092", price: 49.99 };
const isValid = validate(testPayload);
if (isValid) {
console.log("JSON is 100% compliant with Schema!");
} else {
console.error("Validation Errors:", validate.errors);
}
2. Python Backend Validation via jsonschema
import jsonschema
from jsonschema import validate, ValidationError
schema = {
"type": "object",
"properties": {
"userId": {"type": "integer", "minimum": 1},
"status": {"type": "string", "enum": ["active", "suspended"]}
},
"required": ["userId", "status"]
}
payload = {"userId": 42, "status": "active"}
try:
validate(instance=payload, schema=schema)
print("Python Schema Verification: PASSED")
except ValidationError as e:
print(f"Validation Failure: {e.message} at path: {list(e.path)}")
Comparison Matrix: JSON Schema vs Other Contract Standards
| Metric / Feature | JSON Schema (2020-12) | Zod (TypeScript) | XML Schema (XSD) | Protocol Buffers |
|---|---|---|---|---|
| Language Portability | Universal (JSON-based) | TypeScript / JavaScript only | XML-based (Java/C#) | Multi-language (IDL) |
| OpenAPI Compatibility | Native 1:1 Standard | Requires zod-to-openapi | None | Requires gRPC-Gateway |
| Execution Performance | Ultra-Fast (JIT compiled) | Very Fast | Slow (Heavy XML DOM) | Fastest (Native C++ binary) |
| Type Generation | json-schema-to-typescript | Native z.infer<T> | JAXB xjc compiler | protoc compiler |
Critical Edge Cases & Common Pitfalls
1. The additionalProperties: false Trap with allOf
When combining schemas using allOf:
{
"allOf": [
{ "$ref": "#/$defs/BaseUser" },
{ "$ref": "#/$defs/AdminUser" }
],
"additionalProperties": false
}
In JSON Schema Draft-07, additionalProperties: false evaluates properties independently on the local object, causing all properties from BaseUser and AdminUser to be flagged as illegal additional properties!
- Solution: In modern Draft 2020-12, use
unevaluatedProperties: false, which tracks evaluated properties across all sub-schemas cleanly.
2. Regular Expression Denial of Service (ReDoS)
Defining unanchored or catastrophically backtracking regular expressions inside the pattern keyword (e.g. ^([a-zA-Z0-9]+)+$) enables malicious clients to send payloads that lock up the validator's CPU thread for minutes. Always test regular expressions with linear-time regex engines.