YAML Schema Validation: Ajv, jsonschema and Editor Setup
Validate YAML with JSON Schema in Node (js-yaml + Ajv) and Python (PyYAML + jsonschema), with the real error messages, editor schema comments, and the Norway problem.
On this page ⌄
YAML has no schema language of its own. The practical approach is to parse the file into plain data and validate that data with JSON Schema, because a parsed YAML document is just objects, arrays, strings, numbers, booleans and null. This guide runs the same schema and the same broken config through Node and Python, shows the exact error messages, and covers the traps that happen before validation even starts.
The test case
One config file with five mistakes:
database:
host: localhost
port: "5432"
ssl: true
server:
port: 80
logging:
level: verbose
And this JSON Schema (draft-07, saved as schema.json):
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["database", "server"],
"additionalProperties": false,
"properties": {
"database": {
"type": "object",
"required": ["host", "port", "name"],
"properties": {
"host": { "type": "string" },
"port": { "type": "integer", "minimum": 1, "maximum": 65535 },
"name": { "type": "string", "minLength": 1 }
}
},
"server": {
"type": "object",
"required": ["port"],
"properties": { "port": { "type": "integer", "minimum": 1024, "maximum": 65535 } }
},
"logging": {
"type": "object",
"properties": { "level": { "type": "string", "enum": ["debug", "info", "warn", "error"] } }
}
}
}
The mistakes: port is a quoted string, name is missing, ssl is an unknown top-level key, server.port is below 1024, and logging.level is not in the enum.
Node: js-yaml + Ajv
import { readFileSync } from 'node:fs';
import { load } from 'js-yaml';
import Ajv from 'ajv';
const ajv = new Ajv({ allErrors: true });
const validate = ajv.compile(JSON.parse(readFileSync('schema.json', 'utf8')));
const data = load(readFileSync('config.yaml', 'utf8'));
if (!validate(data)) {
for (const e of validate.errors) console.log(`${e.instancePath || '(root)'} ${e.message}`);
process.exitCode = 1;
}
Use the named load import: js-yaml 5 has no default export, so the common import yaml from 'js-yaml' fails with "does not provide an export named 'default'". Output with allErrors: true:
(root) must NOT have additional properties
/database must have required property 'name'
/database/port must be integer
/server/port must be >= 1024
/logging/level must be equal to one of the allowed values
Without allErrors, Ajv stops at the first failure and you fix errors one run at a time. Each error object also carries params, which holds what the message omits: for additionalProperties it is {"additionalProperty":"ssl"}, for required it is {"missingProperty":"name"}, and for enum it is the allowedValues list. Print those, or the "(root) must NOT have additional properties" line will not tell you which key to delete.
Python: PyYAML + jsonschema
import json, yaml
from jsonschema import Draft7Validator
schema = json.load(open("schema.json"))
data = yaml.safe_load(open("config.yaml"))
for e in sorted(Draft7Validator(schema).iter_errors(data), key=lambda e: list(e.path)):
print("/".join(map(str, e.path)) or "(root)", "->", e.message)
(root) -> Additional properties are not allowed ('ssl' was unexpected)
database -> 'name' is a required property
database/port -> '5432' is not of type 'integer'
logging/level -> 'verbose' is not one of ['debug', 'info', 'warn', 'error']
server/port -> 80 is less than the minimum of 1024
Python's messages name the offending key and value, so they are friendlier than Ajv's defaults. Always use yaml.safe_load, never yaml.load on untrusted input.
pydantic is stricter about extras but looser about types
If you prefer models to schema files, pydantic 2 works on the same parsed dict:
class Database(BaseModel):
host: str
port: int = Field(ge=1, le=65535)
name: str
class Config(BaseModel):
model_config = ConfigDict(extra="forbid")
database: Database
On the same data (database only, plus ssl: true) it reports:
database.name | Field required | missing
ssl | Extra inputs are not permitted | extra_forbidden
Notice what is absent: the string '5432' for port produced no error. Pydantic's default lax mode coerces numeric strings to int, while JSON Schema rejects them. If a quoted port must be an error in your config, use JSON Schema or pydantic strict mode.
Error message cheat table
| Ajv message | Python jsonschema message | Usual fix |
|---|---|---|
| must have required property 'name' | 'name' is a required property | Add the key, or remove it from required |
| must be integer | '5432' is not of type 'integer' | Remove the quotes in the YAML |
| must NOT have additional properties | Additional properties are not allowed | Delete the key, or fix a typo in its name |
| must be >= 1024 | 80 is less than the minimum of 1024 | Change the value or the schema bound |
| must be equal to one of the allowed values | 'verbose' is not one of [...] | Pick a listed value |
Traps that happen before validation
Validation sees what the YAML parser produced, not what you typed. These are all verified with PyYAML 6.0.3 (YAML 1.1 rules) and js-yaml 5.5.0 and 4.3.2 (YAML 1.2 core rules).
The Norway problem. In YAML 1.1, unquoted NO, no, off, yes and on are booleans. PyYAML on country: NO gives {'country': False}. A schema that says country is a string then fails with False is not of type 'string', and a pattern such as ^[A-Z]{2}$ never even gets a string to test. js-yaml follows YAML 1.2 and returns 'NO', so the same file validates in Node and fails in Python. Quote the value (country: "NO") if any consumer might use a YAML 1.1 parser. The YAML to JSON Converter uses js-yaml 4, so it shows you the 1.2 reading: the string NO.
on: becomes True. PyYAML parses a GitHub Actions workflow key on: as the boolean True, so the lookup data["on"] raises KeyError. Real output: {True: {'push': None}}. js-yaml keeps the string key on.
Sexagesimal numbers. PyYAML turns 1:30 into 90 and 22:22 into 1342. js-yaml leaves '22:22' as a string. This matters for port mappings in Docker Compose, where you should always quote "22:22".
Version-like numbers. ver: 1.10 parses to the float 1.1 in both parsers. Quote versions.
Duplicate keys. PyYAML silently keeps the last value: a: 1 then a: 2 gives {'a': 2} and no error. js-yaml throws duplicated mapping key (2:1). JSON Schema cannot catch this because the duplicate is gone by the time validation runs, so rely on a parser that rejects it. The YAML Validator reports Line 2, Col 1: Duplicate key "a".
Anchors and merge keys expand first. A <<: *base merge is resolved by the parser, so the schema validates the merged result. In js-yaml 4.3.2, prod: {<<: *b, host: x} becomes { port: 5432, host: 'x' }. js-yaml 5.5.0 in default mode leaves << as a literal key, so merge behaviour differs between major versions. The site's YAML Validator rejects anchors, aliases and merge keys outright (Anchors, aliases, tags and merge keys are not supported), so use a real parser plus your schema for files that rely on them.
Editor validation with yaml-language-server
The Red Hat YAML extension for VS Code (which embeds yaml-language-server) validates while you type. Two ways to attach a schema:
# yaml-language-server: $schema=./schema.json
database:
host: localhost
port: 5432
or in .vscode/settings.json:
{
"yaml.schemas": {
"./schema.json": "config.yaml",
"https://json.schemastore.org/github-workflow.json": ".github/workflows/*.yml"
}
}
The SchemaStore URL above responds (an HTTP 301 to its current location) as of 2026-11-02. SchemaStore also publishes schemas for Docker Compose and GitHub Actions action files, and the extension applies many of them automatically by filename. Not run: the editor. The editor behaviour described follows the extension's documented settings, not a screenshot.
If you have sample JSON and need a starting schema, the JSON to JSON Schema generator drafts one you can tighten by hand, and the JSON Validator checks converted output.
FAQ
How do I validate a YAML file against a JSON Schema?
Parse it to an object (js-yaml or PyYAML), then pass the object to Ajv or jsonschema as shown above. YAML itself cannot carry the schema.
Does Ajv support YAML directly? No. Ajv validates JavaScript values. Parse the YAML first and validate the result.
Why does my YAML validate in Node but fail in Python?
Usually a YAML 1.1 versus 1.2 difference: NO, yes, on and 1:30 parse as booleans or numbers in PyYAML but as strings in js-yaml. Quote the values that must be strings.
Can the schema detect duplicate keys? No. Duplicates are resolved by the parser before validation. Use a parser that errors on them.
Tested
Run on 2026-11-02 on Node 25.8.0 with ajv 8.20.0, js-yaml 5.5.0 (and 4.3.2 for the merge-key and converter checks), Python 3.11.15 with PyYAML 6.0.3, jsonschema 4.26.0 and pydantic 2.14.1. All error messages above are copied from those runs. The YAML Validator output was produced by importing the site tool module.
Related tools
YAML Validator
Validate YAML syntax instantly in your browser with detailed error reporting including line and column numbers.
JSON Formatter
Format, validate, and beautify JSON online. 100% client-side, your data never leaves your browser.
HTML Viewer & Formatter
Paste HTML and see it rendered live in a sandboxed preview. Format and beautify messy markup, inline CSS and JS. Desktop, tablet and mobile widths.
JSON Viewer
Explore JSON as a collapsible tree. Paste JSON and navigate nested structures with expand/collapse and JSONPath copy.
Written by Mian Ali Khalid. More guides in Data & Format.