Skip to main content

JSON/YAML schema validation within Jinja2 templates

Project description

JSON Schema Validation within Jinja2 Templates

Tests Python versions PyPI Code style: Black Linter: Ruff Type-checker: mypy

A Jinja2 extension providing a Jinja2 filter and a Jinja2 test for validating data against a JSON/YAML schema within Jinja2 templates.

Installation

  • With pip:

    pip install jinja2-jsonschema
    
    # ... or with YAML support
    pip install jinja2-jsonschema[yaml]
    
  • With poetry:

    poetry add jinja2-jsonschema
    
    # ... or with YAML support
    poetry add jinja2-jsonschema -E yaml
    
  • With pdm:

    pdm add jinja2-jsonschema
    
    # ... or with YAML support
    pdm add jinja2-jsonschema[yaml]
    
  • With pipx (injected into the pipx-managed virtual env of a package):

    pipx inject PACKAGE jinja2-jsonschema
    
    # ... or with YAML support
    pipx inject PACKAGE jinja2-jsonschema[yaml]
    

Usage

The extension provides:

  • A Jinja2 filter which receives a schema file path or schema object as input and returns a jsonschema.ValidationError object when validation fails and an empty string ("") otherwise.
  • A Jinja2 test which receives a schema file path or schema object as input and returns False when validation fails and True otherwise.

The JSON Schema dialect is inferred from the $schema field in the JSON Schema document and, when omitted, defaults to the latest dialect supported by the installed jsonschema library. Both local and remote schemas are supported including schema references and JSON Pointers.

Local schema files are loaded via a Jinja2 loader in which case configuring the Jinja2 environment with a loader is mandatory.

Some example usage of the JSON Schema validation filter and test is this:

from jinja2 import Environment
from jinja2 import FileSystemLoader


env = Environment(
    # Register a loader (only necessary when using local schema files).
    loader=FileSystemLoader("/path/to/templates"),
    # Register the extension.
    extensions=["jinja2_jsonschema.JsonSchemaExtension"],
)

# Example using an inline schema object.
template = env.from_string("{{ age | jsonschema({'type': 'integer', 'minimum': 0}) }}")
template.render(age=30)  # OK
template.render(age=-1)  # ERROR
template = env.from_string("{{ age is jsonschema({'type': 'integer', 'minimum': 0}) }}")
template.render(age=30)  # --> `True`
template.render(age=-1)  # --> `False`

# Example using a local schema file.
template = env.from_string("{{ age | jsonschema('age.json') }}")
template.render(age=30)  # OK
template.render(age=-1)  # ERROR
template = env.from_string("{{ age is jsonschema('age.json') }}")
template.render(age=30)  # --> `True`
template.render(age=-1)  # --> `False`

# Example using a remote schema file.
template = env.from_string("{{ age | jsonschema('https://example.com/age.json') }}")
template.render(age=30)  # OK
template.render(age=-1)  # ERROR
template = env.from_string("{{ age is jsonschema('https://example.com/age.json') }}")
template.render(age=30)  # --> `True`
template.render(age=-1)  # --> `False`

Usage with Copier

The extension integrates nicely with Copier, e.g. for validating complex JSON/YAML answers in the Copier questionnaire. For this, add the extension as a Jinja2 extension in copier.yml and use the Jinja2 filter in the validator field of a Copier question. For instance:

_jinja_extensions:
  - jinja2_jsonschema.JsonSchemaExtension

complex_question:
  type: json # or `yaml`
  validator: "{{ complex_question | jsonschema('schemas/complex.json') }}"

In this example, a local schema file schemas/complex.json is used whose path is relative to the template root. To prevent copying schema files to the generated project, they should be either excluded

+_exclude:
+  - schemas/
 _jinja_extensions:
   - jinja2_jsonschema.JsonSchemaExtension

or the project template should be located in a subdirectory such as template/:

+_subdirectory_: template
 _jinja_extensions:
   - jinja2_jsonschema.JsonSchemaExtension

Finally, template consumers need to install the extension along with Copier. For instance with pipx:

pipx install copier
pipx inject copier jinja2-jsonschema

Contributions

Contributions are always welcome via filing issues or submitting pull requests. Please check the contribution guide for more details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

jinja2_jsonschema-0.2.1.tar.gz (5.9 kB view details)

Uploaded Source

Built Distribution

jinja2_jsonschema-0.2.1-py3-none-any.whl (6.5 kB view details)

Uploaded Python 3

File details

Details for the file jinja2_jsonschema-0.2.1.tar.gz.

File metadata

  • Download URL: jinja2_jsonschema-0.2.1.tar.gz
  • Upload date:
  • Size: 5.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/4.0.1 CPython/3.11.4

File hashes

Hashes for jinja2_jsonschema-0.2.1.tar.gz
Algorithm Hash digest
SHA256 5d5f8a2f9bbaaea66a7e26b501c4f38b1b75259affe545e8b5c2058a04044dc2
MD5 4ebecc678068598365d76bad4e5ea884
BLAKE2b-256 dd2a128c68717fc2e923a08885b7caa7ac2ce0e35df2f2c5c4bc93304ba258a6

See more details on using hashes here.

File details

Details for the file jinja2_jsonschema-0.2.1-py3-none-any.whl.

File metadata

File hashes

Hashes for jinja2_jsonschema-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 27cb36be566e97f2434ce3a424db7dd1aabcf22fc04148af2f99e5bca8e63f9d
MD5 7b51febe196882764e57f23fdf375eac
BLAKE2b-256 a5020b82e560fc1b3c144b3c49b10d11952b5dd42160e7d6e697b0fa295a9b63

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page