
One sentence summary
This post will show you how to use a locally stored JSON schema to validate a JSON document.
Set up
In the context of this post, locally stored means the files are located somewhere on your computer. For the examples used here, both the schema and the document are in the same directory.
I used VS Code with it’s default JSON capabilities to create, edit and validate the JSON files. The files can be found on GitHub.
Here is the JSON schema:
{
"$schema": "http://json-schema.org/draft-07/schema",
"title": "ColoumboEpisodes",
"properties": {
"name": {
"type": "string",
"description": "The name of the episode",
"minLength": 10,
"maxLength": 100
},
"synopsis": {
"type": "string",
"description": "Brief overview of the episode. No spoilers",
"minLength": 10
},
"villain": {
"type": "string",
"description": "The name of the murderer"
},
"season": {
"type": "number",
"description": "The season that the episode was shown",
"maximum": 99
},
"reboot": {
"type": "boolean",
"description": "true is this episode was made when the show returned in 1989 otherwise false "
}
},
"required": [
"name",
"synopsis",
"villain"
]
}
It ensures that Columbo JSON documents conform to a number requirements. The name of the episode, a synopsis and the name of the leading bad guy are all mandatory properties. It also defines other constraints such as the data types and the maximum allowable value.
To reference a schema in a JSON document you add the following to the document root:
"$schema": "Path to Schema"
In the context of this post this becomes:
"$schema": "./columboSchema.json"
Where columboSchema.json is the filename of the schema and it is located in the same directory as the JSON document that references it.
The complete JSON document below shows on line 2 the reference to the schema.
{
"$schema": "./columboSchema.json",
"name": "An Exercise in Fatality",
"synopsis": "A health club owner murders one of his franchisees.",
"villain": "Milo Janus",
"reboot": true,
"season": 4
}
Schema validation
Opening the JSON document shown above in VS Code shows that this document meets the contract specified by the schema and no problems are detected:

However if the document is edited so it no longer conforms to the schema, VS Code indicates the problems:

VS Code reports several problems with this document. One of the required properties are missing, the datatype for reboot is of the wrong type (A string is used instead of a boolean) and the final problem is that the value for season exceeds the maximum allowed.
Acknowledgements
The book Introduction to JavaScript Object Notation: A To-the-Point Guide to JSON by Lindsay Bassett for getting me up and running with JSON.