Did you know ... Search Documentation:
json_schema.pl -- JSON Schema reader and validator
PublicShow source

This module provides a JSON Schema reader and validator. This module is based on the 2020-12 draft of the specification.

The API consists of two primitives and a simple high level predicate (json_validate/3):

  • json_compile_schema/3 translates a file or parsed JSON schema data into a Prolog term that represents the schema in a way that is more suitable for checking a JSON document.
  • json_check/3 validates a document against the compiled schema.

Status

The implementation is validated against https://github.com/json-schema-org/JSON-Schema-Test-Suite.git. It fails 4 out of 1,261 tests. Issues:

  • $dynamicRef fails 3 tests, probably mixing up physical context and resolution context that defines the dynamic scopes.
  • There is no support for non-default vocabulary selection.

The current implementation is the result of an incremental process. It should be refactored to make it a cleaner translation of the specification.

Predicates

Source json_validate(+SchemaFile, +DataDict, +Options) is det
Given a file holding a JSON Schema and a Prolog dict holding JSON data, validate the data against the schema. Options are passed to json_compile_schema/3 and json_check/3.
throws
- error(Formal, json_path(Path)), where Path is a list of properties from the root element to the culprit element. Formal is typically a type, domain or existence error. This file contains the message hooks to generate a human readable error from these exceptions using print_message/2.
Source json_compile_schema(+Input, -Type, +Options) is det
Load and translated a JSON Schema. Input is either a file name, a specification for absolute_file_name/3 or the output of json_read_dict/2.

If Input is a file name, the loaded and compiled schema is cached. Reusing the cache validates the modification file of the schema file and reloads it if the file's time stamp has changed. Note that true and false are valid schemas and cannot be used as file names.

Source json_check(+Spec, ?JSON, +Options) is semidet
Validate a JSON object. Spec is a Prolog representation of the schema that is optimized for validation. This representation is derived from JSON data using json_compile_schema/3. Options:
on_error(Mode)
What to do if an error is found. Defined modes are
error
Raise an exception. This is the default. Note that only the first error is reported this way.
warning
Print a message
silent
Fail
value_string_as(Type)
Same as for json_read/3.

This predicate is often used through validate_json_dict/3, which mantains a cached mapping from the JSON Schema to Spec.