Validador JSON Schema

Valide documentos JSON contra JSON Schema com relatório de erros por caminho

What is JSON Schema Validation?

JSON Schema validation is the process of checking whether a JSON instance document conforms to the constraints defined in a JSON Schema. While basic JSON validation answers "is this syntactically correct?", schema validation answers a much richer question: "does this data match the expected structure, types, and constraints?" A JSON Schema defines the shape of your data — required properties, allowed types, string patterns, numeric ranges, array lengths, enum values, and nested object structures. This tool takes a JSON document and a JSON Schema, then reports whether the instance satisfies every constraint, providing detailed error paths when it does not.

Schema validation is essential in API development, configuration management, and data pipelines. It catches structural errors that syntax validation cannot: a missing required field, a string where a number is expected, an array item that violates its item schema, or a property value outside the allowed enumeration. By validating data at boundaries — API request bodies, configuration files, event payloads — you prevent malformed data from propagating through your system and causing hard-to-debug failures downstream.

How JSON Schema Validation Works

JSON Schema validation evaluates a JSON instance against a schema document by traversing the schema's constraint keywords and checking each one against the corresponding value in the instance. The process is recursive: when a schema defines properties for an object, the validator descends into each property and applies its sub-schema. When it defines items for an array, the validator checks every array element against the item schema. Validation produces either a pass (the instance conforms) or a list of errors, each annotated with a JSON Pointer path to the failing property.

The core validation keywords cover type checking (type), required properties (required), string constraints (minLength, maxLength, pattern, format), numeric constraints (minimum, maximum, multipleOf), array constraints (minItems, maxItems, uniqueItems, items), object constraints (properties, additionalProperties, patternProperties), and enumeration (enum, const). Composition keywords like allOf, anyOf, oneOf, and not allow combining multiple schemas with logical operators for complex validation scenarios.

Validation errors include a JSON Pointer path (e.g., /address/zipCode) that identifies exactly which property failed, the constraint keyword that was violated, and the expected vs actual value. This precision makes it straightforward to locate and fix data issues, even in deeply nested documents with hundreds of properties.

Common Validation Keywords and Their Behavior

Understanding the most frequently used schema keywords helps you write schemas that catch real errors without being overly restrictive:

  • type: Restricts a value to one or more JSON types. Accepts "string", "number", "integer", "boolean", "array", "object", or "null". Use an array like ["string", "null"] for nullable fields.
  • required: An array of property names that must be present in an object. Missing a required property is the most common validation error in API request bodies.
  • pattern: A regular expression that a string value must match. Useful for validating formats like phone numbers, postal codes, or custom identifiers that the built-in format keyword does not cover.
  • enum: An array of allowed values. The instance must exactly equal one of the listed values. Commonly used for status fields, country codes, or configuration options.
  • items: Defines the schema that every element in an array must satisfy. Can be a single schema (all items match the same shape) or, in Draft 2020-12, a prefixItems array for tuple validation where each position has a different schema.
  • additionalProperties: Controls whether an object can contain properties beyond those listed in properties. Set to false to enforce strict shapes, or provide a schema to constrain any extra properties.
  • format: Provides semantic validation for strings — "email", "uri", "date-time", "ipv4", "uuid", etc. Note that format validation is optional per the specification; not all validators enforce it by default.

Combining these keywords lets you express precise data contracts. A well-written schema serves as both validation logic and documentation — developers can read the schema to understand exactly what data an API endpoint expects without consulting external documentation.

Validation Error Interpretation and Debugging

When validation fails, the error output contains structured information to help you fix the data. Each error includes a path (JSON Pointer to the failing value), a keyword (the constraint that failed), and a message describing the mismatch. For example, an error at path /users/0/email with keyword format means the first user's email field does not match the email format.

Common patterns in validation errors and their fixes:

  • "required property missing" — the object at the indicated path lacks a property listed in the schema's required array. Add the missing property or make it optional by removing it from required.
  • "type mismatch" — the value's type does not match the schema's type constraint. A common case is sending a numeric string ("42") where an integer is expected (42).
  • "pattern mismatch" — the string does not match the regular expression in pattern. Verify that the regex is correct and that the input value matches the expected format.
  • "enum value not allowed" — the value is not in the list of permitted values. Check for typos or case mismatches (enums are case-sensitive).
  • "additional property not allowed" — an extra field exists that is not defined in properties and additionalProperties is false. Either remove the extra field or add it to the schema.

When debugging complex schemas with composition keywords (oneOf, anyOf), the validator may report multiple branches that failed. Read each branch's errors to determine which sub-schema was intended and which specific constraint within it failed.

JSON Schema Versions and Compatibility

JSON Schema has evolved through several drafts, each adding new keywords and refining existing behavior. The most widely used versions are Draft-07 (2018), Draft 2019-09, and Draft 2020-12. When validating, the $schema keyword at the top of a schema document declares which draft it targets, allowing validators to apply the correct rules.

Key differences between drafts that affect validation: Draft 2019-09 introduced unevaluatedProperties and unevaluatedItems for stricter composition validation. Draft 2020-12 replaced the overloaded items keyword with prefixItems for tuple validation and items for additional items. If your schema uses $schema to declare Draft 2020-12 but your validator only supports Draft-07, some keywords may be ignored or misinterpreted.

For most API validation use cases, Draft-07 provides sufficient keywords and has the broadest library support. Choose Draft 2020-12 when you need advanced features like unevaluatedProperties for clean schema inheritance, dynamic references with $dynamicRef, or content media type annotations. This tool supports schemas written against any of the major drafts and applies the appropriate validation rules based on the declared $schema URI.

Code Examples

JSON Schema with type checking, required fields, and pattern validation

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "User Profile",
  "type": "object",
  "required": ["id", "email", "role"],
  "properties": {
    "id": {
      "type": "integer",
      "minimum": 1,
      "description": "Unique user identifier"
    },
    "email": {
      "type": "string",
      "format": "email",
      "description": "User's email address"
    },
    "name": {
      "type": "string",
      "minLength": 1,
      "maxLength": 100
    },
    "role": {
      "type": "string",
      "enum": ["admin", "editor", "viewer"]
    },
    "tags": {
      "type": "array",
      "items": { "type": "string" },
      "uniqueItems": true,
      "maxItems": 10
    },
    "address": {
      "type": "object",
      "properties": {
        "street": { "type": "string" },
        "zipCode": {
          "type": "string",
          "pattern": "^[0-9]{5}(-[0-9]{4})?$"
        },
        "country": {
          "type": "string",
          "minLength": 2,
          "maxLength": 2
        }
      },
      "required": ["street", "country"]
    }
  },
  "additionalProperties": false
}

Output:

// Valid instance:
{
  "id": 42,
  "email": "alice@example.com",
  "role": "admin",
  "tags": ["developer", "lead"],
  "address": { "street": "123 Main St", "zipCode": "90210", "country": "US" }
}
// → Validation passed ✓

// Invalid instance:
{
  "id": "forty-two",
  "email": "not-an-email",
  "role": "superuser",
  "tags": ["a", "a"]
}
// → Errors:
//   /id — type: expected integer, got string
//   /email — format: must be a valid email
//   /role — enum: must be one of [admin, editor, viewer]
//   /tags — uniqueItems: array items must be unique
//   (root) — required: missing property "role" → already present but invalid

Validating JSON data against a schema in JavaScript

import Ajv from 'ajv';
import addFormats from 'ajv-formats';

const ajv = new Ajv({ allErrors: true });
addFormats(ajv);

const schema = {
  type: 'object',
  required: ['name', 'age'],
  properties: {
    name: { type: 'string', minLength: 1 },
    age: { type: 'integer', minimum: 0, maximum: 150 },
    email: { type: 'string', format: 'email' }
  },
  additionalProperties: false
};

const validate = ajv.compile(schema);

const data = { name: 'Alice', age: 30, email: 'alice@example.com' };
const valid = validate(data);

if (valid) {
  console.log('Validation passed');
} else {
  for (const error of validate.errors) {
    console.log(`${error.instancePath} — ${error.keyword}: ${error.message}`);
  }
}

Standards & Specifications

Perguntas Frequentes

What does the JSON Schema validator check?

It validates a JSON document against a JSON Schema and reports whether the instance matches the expected structure, required fields, and value constraints.

Can it validate both the schema and the JSON input?

Yes. The tool parses both inputs first, so you get clear errors for malformed JSON in either the instance or the schema before schema validation runs.

Does it support object, array, and boolean schemas?

Yes. The validator accepts standard JSON Schema objects and boolean schemas, which are valid in modern JSON Schema drafts.

What kind of errors does it show?

It shows Ajv validation errors with the instance path and a human-readable message, so you can see exactly which field failed and why.

Is my schema or JSON sent to a server?

No. Validation happens entirely in your browser. The schema and the data stay local, which is the correct amount of paranoia for sensitive API contracts.