Basic Schema Structure

A JSON Schema is itself a JSON object with keywords describing valid instances. The 'type' keyword specifies the expected type. 'Properties' defines the schema for each field. 'Required' lists fields that must be present. 'additionalProperties: false' rejects fields not defined in the schema.

Type Constraints and Patterns

Schemas can constrain values beyond type: 'minimum' and 'maximum' for numbers, 'minLength' and 'maxLength' for strings, 'pattern' for regex matching, 'enum' for a fixed set of allowed values.

Composition with allOf, anyOf, oneOf

Schemas can combine using logical operators. 'allOf' requires all listed schemas to match. 'anyOf' requires at least one to match. 'oneOf' requires exactly one to match. These enable polymorphic data structures.

Validation in Practice

The Ajv library is the most widely used JavaScript JSON Schema validator. It compiles schemas to optimized validation functions and runs entirely in the browser for client-side validation. The same schemas work server-side too, allowing you to write schema once and validate in both places.

Key Takeaway

JSON Schema is worth the investment for any API you maintain or consume with complex data. It documents expectations, catches errors early, and enables auto-generated documentation and client SDKs.