Validating config files with JSON Schema
A config file can be syntactically right and still wrong. JSON Schema lets you declare types, required keys, ranges and patterns so that wrongness is caught before deployment.
A minimal schema
type and required alone catch half the problems. Adding properties with a type per key catches typos and type mistakes together.
additionalProperties: false turns any key not in the schema into an error, which is the fastest way to catch a mistyped key.
{
"type": "object",
"required": ["service", "replicas"],
"properties": {
"service": { "type": "string", "minLength": 2 },
"replicas": { "type": "integer", "minimum": 1, "maximum": 20 }
},
"additionalProperties": false
}
Combinations worth memorising
Version strings belong in pattern, fixed choices in enum, and repeated shapes in $defs with $ref. Once a shape appears three times, give it a definition.
anyOf and oneOf express alternatives: anyOf needs at least one match, oneOf exactly one.
| Goal | Keywords |
|---|---|
| required keys | required |
| allowed values | enum, const |
| ranges | minimum, maximum, minLength, minItems |
| shape | pattern, format (annotation) |
| reuse | $defs with $ref |
| alternatives | anyOf, oneOf, not |
Reading the result
Errors are reported as JSON paths, such as $.spec.replicas, so you can jump straight to the spot in the file.
When anyOf fails, the errors of each branch are shown too; the branch that came closest usually shows what to fix.
Questions
Does format check the value?
Here format is treated as an annotation only. To enforce an email or date shape, write a pattern.
Can a schema reference a remote document?
Remote $ref URLs are not fetched. Put the definitions you need in $defs or definitions in the same document.
Sources
Every example here can be pasted into the converter as it is.
Open the converter