jsonchema: Custom type, format and validator in Python

jsonschema is a great library for validating JSON data with JSON schema in Python. It also allows you to specify custom JSON schema types, formats and even validators. Unfortunately, the documentation is not very clear about the way how to create customized validators.

This guide will show you an example how to create a custom validator, that will add:

  • Type float - jsonschema knows by default only type number, which covers all numbers (integers, floating point numbers, complex numbers, ...).
  • Format even - limiting any number to even numbers only.
  • Validator is_positive - accepting only positive numbers when set to True and all the rest if set to False.

Custom jsonschema validator class

To add support for custom type, format, and validator, we must create a new IValidator class. We will base it on Draft4Validator. Then we will create a function that will work as validator for positive numbers, create another function as a format checker for even numbers and lastly, add float as a new type.

We will write the example as a unit test TestCase, so we can easily test at the end that our new validator works as expected.

Schema definition

Let us first add required imports and define the schema that we will use for checking our JSON data:

This schema will accept JSON in format {'value': number}, where number is even, positive and float (2.0, 4.0, etc.).

Custom JSON schema validator

Next, we will define a validator, that will validate a (non-)positive number based on its settings. The validator can be set to a Boolean value. Validator must be a function, that accepts exactly 4 arguments in this order:

  • validator - instance of validator that is calling this method.
  • value - value set to the validator in the schema (in our case True/False).
  • instance - value that is being validated (in our case the number).
  • schema - the part of schema where this validator is used (in our case the properties/value dict).
A validator must yield a ValidationError when the validation fails. You can get inspired in jsonschema._validators. Let us add the new validator among existing ones and create a new IValidator class using this validator:

Custom JSON schema format checker

Creating a custom format checker again requires defining a function, that will check the format. This method can be the registered either globally for all FormatChecker instances or tied to a single instance. Let us define a format checker to check that a number is even. First, we need a FormatChecker instance. Then we will use this instance as a decorator for the format checking function. The function must accept exactly one argument - the value to check.

A format checker method can also raise exceptions to notify format check failure. To do this, provide the decorator with expected Exception class or a tuple of expected classes. The downside of this approach is that the method has to always return some value, otherwise no exception will be still treated as a failure.

You can also register the format globally for all FormatChecker instances.

Custom type in JSON schema

Now we will put all the previous example together to create an IValidator instance, that will have a custom validator is_positive and custom number format even. We will also add type float.

Checking the result

To check that our new validator instance really accepts only positive, even float, let us add some unit test assertions.

Complete example

Související články / Related posts:

1 Komentářů / Comments

Zanechte komentář / Leave a comment

Your email address will not be published. Required fields are marked *