JSON guide · 4 min read
How to Validate JSON Against a JSON Schema
Validate JSON structure and values against a schema, read validation errors by path and design useful positive and negative contract tests.
Syntax and schema validation answer different questions
A JSON parser asks whether the text is syntactically valid. JSON Schema asks whether the parsed value satisfies declared structural rules. A document can pass syntax validation and still be unusable because a required property is missing or a field has the wrong type.
Valid JSON, possibly invalid for the contract:
{"name":"Asha","age":"thirty-three"}Start with a small explicit schema
Use type for the expected JSON kind, properties for known fields and required for properties that must be present. Add constraints gradually so each rule has a clear reason.
{
"type": "object",
"required": ["name", "age"],
"properties": {
"name": {"type": "string", "minLength": 1},
"age": {"type": "integer", "minimum": 0}
}
}Read errors by instance path and keyword
A useful validator reports where the failing value appears and which rule it violated. Fix broad structural errors first because one wrong type can produce several downstream messages.
Required and nullable are separate decisions
required controls whether a property exists. It does not automatically determine whether a present value may be null. Test missing and null cases independently and express nullability explicitly when allowed.
Validate arrays at collection and item level
An array rule can constrain item types, count and sometimes uniqueness. Merely declaring type array does not stop mixed element shapes unless the item schema does.
Build positive and negative contract tests
A useful validation suite includes examples that should pass and targeted failures for missing fields, wrong types, invalid enum values and boundary conditions. Negative tests demonstrate that the schema rejects the mistakes it was created to catch.
- A complete valid example.
- Missing critical fields.
- Wrong types.
- Numeric and length boundaries.
- Unexpected enum values and extra properties when relevant.
Keep validator output for diagnostics
Raw validator messages are developer diagnostics and can expose internal paths. Applications should map them to appropriate user-facing messages while retaining safe detailed diagnostics for debugging.
Remember that object properties are allowed unless you restrict them
Defining properties does not automatically reject every other key. In common JSON Schema drafts, additional object properties remain allowed unless the schema restricts them with keywords such as additionalProperties or unevaluatedProperties. This is a frequent reason a payload validates when a developer expected an unknown field to fail.
Choose strictness deliberately. Public APIs often need forward compatibility, while internal configuration may benefit from rejecting misspelled keys immediately. The right setting depends on how the schema evolves and who controls producers and consumers.
{
"type": "object",
"properties": {
"id": { "type": "string" }
},
"required": ["id"],
"additionalProperties": false
}Separate presence, nullability and value constraints
The required keyword controls whether a property must exist. It does not by itself make the property's value non-null. Conversely, a property can be optional but reject null whenever it is present. Model those dimensions independently so the schema matches the API semantics you actually want.
{
"type": "object",
"properties": {
"nickname": { "type": ["string", "null"] },
"email": { "type": "string" }
},
"required": ["email"]
}Check validator settings for formats and draft support
Keywords are interpreted in the context of a JSON Schema draft and validator implementation. In particular, format handling can be configured differently across validators, and unsupported vocabularies may be ignored or rejected. Record the draft and validator settings in CI so local and production validation do not silently disagree.
When validation matters for security or correctness, test the validator with known failing examples rather than assuming that loading a schema proves every keyword is being enforced the way you expect.
Read validation errors from the deepest useful path
Composition keywords such as oneOf, anyOf and allOf can produce several nested errors for one bad value. Start with the instance path and failing keyword, then inspect the parent composition error. Fixing only the top-level message can hide the specific branch that failed.
Primary sources
References and specifications
- JSON Schema — Draft 2020-12 specification
Specification for the current JSON Schema core and validation vocabularies.
- Ajv documentation
Validator documentation relevant to the Ajv-based validation used by JSON Hearth.
Common questions
Frequently asked questions
Why does valid JSON fail schema validation?
The text parses correctly, but one or more values violate the structure or constraints declared by the schema.
Does required mean a field cannot be null?
No. required controls presence. Nullability is a separate type or schema decision.
Can JSON Schema validate every business rule?
No. It handles many structural constraints, while cross-field, database or external business rules may still require application code.