Schema Validation¶
The Basics¶
The simplest way to validate an instance under a given schema is to use the
validate()
function.
-
jsonschema.
validate
(instance, schema, cls=None, *args, **kwargs)[source]¶ Validate an instance under the given schema.
>>> validate([2, 3, 4], {"maxItems": 2}) Traceback (most recent call last): ... ValidationError: [2, 3, 4] is too long
validate()
will first verify that the provided schema is itself valid, since not doing so can lead to less obvious error messages and fail in less obvious or consistent ways.If you know you have a valid schema already, especially if you intend to validate multiple instances with the same schema, you likely would prefer using the
IValidator.validate
method directly on a specific validator (e.g.Draft7Validator.validate
).- Parameters
instance – The instance to validate
schema – The schema to validate with
cls (IValidator) – The class that will be used to validate the instance.
If the
cls
argument is not provided, two things will happen in accordance with the specification. First, if the schema has a $schema property containing a known meta-schema 1 then the proper validator will be used. The specification recommends that all schemas contain $schema properties for this reason. If no $schema property is found, the default validator class is the latest released draft.Any other provided positional and keyword arguments will be passed on when instantiating the
cls
.- Raises
jsonschema.exceptions.ValidationError – is invalid
jsonschema.exceptions.SchemaError – is invalid
Footnotes
- 1
known by a validator registered with
jsonschema.validators.validates
- 2
For information on creating JSON schemas to validate your data, there is a good introduction to JSON Schema fundamentals underway at Understanding JSON Schema
The Validator Interface¶
jsonschema
defines an (informal) interface that all validator
classes should adhere to.
-
class
jsonschema.
IValidator
(schema, types=(), resolver=None, format_checker=None)¶ - Parameters
schema (dict) – the schema that the validator object will validate with. It is assumed to be valid, and providing an invalid schema can lead to undefined behavior. See
IValidator.check_schema
to validate a schema first.resolver – an instance of
RefResolver
that will be used to resolve $ref properties (JSON references). If unprovided, one will be created.format_checker – an instance of
FormatChecker
whoseFormatChecker.conforms
method will be called to check and see if instances conform to each format property present in the schema. If unprovided, no validation will be done for format. Certain formats require additional packages to be installed (ipv5, uri, color, date-time). The required packages can be found at the bottom of this page.types –
Deprecated since version 3.0.0: Use
TypeChecker.redefine
andjsonschema.validators.extend
instead of this argument.See Validating With Additional Types for details.
If used, this overrides or extends the list of known types when validating the type property.
What is provided should map strings (type names) to class objects that will be checked via
isinstance
.
-
META_SCHEMA
¶ An object representing the validator’s meta schema (the schema that describes valid schemas in the given version).
-
VALIDATORS
¶ A mapping of validator names (
str
s) to functions that validate the validator property with that name. For more information see Creating or Extending Validator Classes.
-
TYPE_CHECKER
¶ A
TypeChecker
that will be used when validating type properties in JSON schemas.
-
schema
¶ The schema that was passed in when initializing the object.
-
DEFAULT_TYPES
¶ Deprecated since version 3.0.0: Use of this attribute is deprecated in favor of the new
type checkers
.See Validating With Additional Types for details.
For backwards compatibility on existing validator classes, a mapping of JSON types to Python class objects which define the Python types for each JSON type.
Any existing code using this attribute should likely transition to using
TypeChecker.is_type
.
-
classmethod
check_schema
(schema)¶ Validate the given schema against the validator’s
META_SCHEMA
.- Raises
jsonschema.exceptions.SchemaError
if the schema is invalid
-
is_type
(instance, type)¶ Check if the instance is of the given (JSON Schema) type.
- Return type
- Raises
jsonschema.exceptions.UnknownType
iftype
is not a known type.
-
is_valid
(instance)¶ Check if the instance is valid under the current
schema
.- Return type
>>> schema = {"maxItems" : 2} >>> Draft3Validator(schema).is_valid([2, 3, 4]) False
-
iter_errors
(instance)¶ Lazily yield each of the validation errors in the given instance.
- Return type
an
collections.Iterable
ofjsonschema.exceptions.ValidationError
s
>>> schema = { ... "type" : "array", ... "items" : {"enum" : [1, 2, 3]}, ... "maxItems" : 2, ... } >>> v = Draft3Validator(schema) >>> for error in sorted(v.iter_errors([2, 3, 4]), key=str): ... print(error.message) 4 is not one of [1, 2, 3] [2, 3, 4] is too long
-
validate
(instance)¶ Check if the instance is valid under the current
schema
.- Raises
jsonschema.exceptions.ValidationError
if the instance is invalid
>>> schema = {"maxItems" : 2} >>> Draft3Validator(schema).validate([2, 3, 4]) Traceback (most recent call last): ... ValidationError: [2, 3, 4] is too long
All of the versioned validators that are included with
jsonschema
adhere to the interface, and implementers of validator classes
that extend or complement the ones included should adhere to it as well. For
more information see Creating or Extending Validator Classes.
Type Checking¶
To handle JSON Schema’s type property, a IValidator
uses
an associated TypeChecker
. The type checker provides an immutable
mapping between names of types and functions that can test if an instance is
of that type. The defaults are suitable for most users - each of the
versioned validators that are included with
jsonschema
have a TypeChecker
that can correctly handle their respective
versions.
-
class
jsonschema.
TypeChecker
(type_checkers=pmap({}))[source]¶ A
type
property checker.A
TypeChecker
performs type checking for anIValidator
. Type checks to perform are updated usingTypeChecker.redefine
orTypeChecker.redefine_many
and removed viaTypeChecker.remove
. Each of these return a newTypeChecker
object.- Parameters
type_checkers (dict) – The initial mapping of types to their checking functions.
-
is_type
(instance, type)[source]¶ Check if the instance is of the appropriate type.
- Parameters
- Returns
Whether it conformed.
- Return type
- Raises
jsonschema.exceptions.UndefinedTypeCheck – if type is unknown to this object.
-
redefine
(type, fn)[source]¶ Produce a new checker with the given type redefined.
- Parameters
type (str) – The name of the type to check.
fn (collections.Callable) – A function taking exactly two parameters - the type checker calling the function and the instance to check. The function should return true if instance is of this type and false otherwise.
- Returns
A new
TypeChecker
instance.
-
redefine_many
(definitions=())[source]¶ Produce a new checker with the given types redefined.
- Parameters
definitions (dict) – A dictionary mapping types to their checking functions.
- Returns
A new
TypeChecker
instance.
-
remove
(*types)[source]¶ Produce a new checker with the given types forgotten.
- Parameters
types (Iterable) – the names of the types to remove.
- Returns
A new
TypeChecker
instance- Raises
jsonschema.exceptions.UndefinedTypeCheck – if any given type is unknown to this object
-
exception
jsonschema.exceptions.
UndefinedTypeCheck
(type)[source]¶ A type checker was asked to check a type it did not have registered.
Raised when trying to remove a type check that is not known to this TypeChecker, or when calling
jsonschema.TypeChecker.is_type
directly.
Validating With Additional Types¶
Occasionally it can be useful to provide additional or alternate types when validating the JSON Schema’s type property.
jsonschema
tries to strike a balance between performance in the common
case and generality. For instance, JSON Schema defines a number
type, which
can be validated with a schema such as {"type" : "number"}
. By default,
this will accept instances of Python numbers.Number
. This includes in
particular int
s and float
s, along with
decimal.Decimal
objects, complex
numbers etc. For
integer
and object
, however, rather than checking for
numbers.Integral
and collections.abc.Mapping
,
jsonschema
simply checks for int
and dict
, since the
more general instance checks can introduce significant slowdown, especially
given how common validating these types are.
If you do want the generality, or just want to add a few specific additional
types as being acceptable for a validator object, then you should update an
existing TypeChecker
or create a new one. You may then create a new
IValidator
via jsonschema.validators.extend
.
class MyInteger(object):
pass
def is_my_int(checker, instance):
return (
Draft3Validator.TYPE_CHECKER.is_type(instance, "number") or
isinstance(instance, MyInteger)
)
type_checker = Draft3Validator.TYPE_CHECKER.redefine("number", is_my_int)
CustomValidator = extend(Draft3Validator, type_checker=type_checker)
validator = CustomValidator(schema={"type" : "number"})
Versioned Validators¶
jsonschema
ships with validator classes for various versions of
the JSON Schema specification. For details on the methods and attributes
that each validator class provides see the IValidator
interface,
which each included validator class implements.
-
class
jsonschema.
Draft7Validator
(schema, types=(), resolver=None, format_checker=None)¶
-
class
jsonschema.
Draft6Validator
(schema, types=(), resolver=None, format_checker=None)¶
-
class
jsonschema.
Draft4Validator
(schema, types=(), resolver=None, format_checker=None)¶
-
class
jsonschema.
Draft3Validator
(schema, types=(), resolver=None, format_checker=None)¶
For example, if you wanted to validate a schema you created against the Draft 6 meta-schema, you could use:
from jsonschema import Draft6Validator
schema = {
"$schema": "https://json-schema.org/schema#",
"type": "object",
"properties": {
"name": {"type": "string"},
"email": {"type": "string"},
},
"required": ["email"]
}
Draft6Validator.check_schema(schema)
Validating Formats¶
JSON Schema defines the format property which can be used to check
if primitive types (string
s, number
s, boolean
s) conform to
well-defined formats. By default, no validation is enforced, but optionally,
validation can be enabled by hooking in a format-checking object into an
IValidator
.
>>> validate("localhost", {"format" : "hostname"})
>>> validate(
... instance="-12",
... schema={"format" : "hostname"},
... format_checker=draft7_format_checker,
... )
Traceback (most recent call last):
...
ValidationError: "-12" is not a "hostname"
-
class
jsonschema.
FormatChecker
(formats=None)[source]¶ A
format
property checker.JSON Schema does not mandate that the
format
property actually do any validation. If validation is desired however, instances of this class can be hooked into validators to enable format validation.FormatChecker
objects always returnTrue
when asked about formats that they do not know how to validate.To check a custom format using a function that takes an instance and returns a
bool
, use theFormatChecker.checks
orFormatChecker.cls_checks
decorators.- Parameters
formats (Iterable) – The known formats to validate. This argument can be used to limit which formats will be used during validation.
-
checkers
¶ A mapping of currently known formats to tuple of functions that validate them and errors that should be caught. New checkers can be added and removed either per-instance or globally for all checkers using the
FormatChecker.checks
orFormatChecker.cls_checks
decorators respectively.
-
classmethod
cls_checks
(format, raises=())¶ Register a decorated function as globally validating a new format.
Any instance created after this function is called will pick up the supplied checker.
- Parameters
format (str) – the format that the decorated function will check
raises (Exception) – the exception(s) raised by the decorated function when an invalid instance is found. The exception object will be accessible as the
jsonschema.exceptions.ValidationError.cause
attribute of the resulting validation error.
-
check
(instance, format)[source]¶ Check whether the instance conforms to the given format.
- Parameters
instance (any primitive type, i.e. str, number, bool) – The instance to check
format (str) – The format that instance should conform to
- Raises
FormatError – if the instance does not conform to
format
-
checks
(format, raises=())[source]¶ Register a decorated function as validating a new format.
- Parameters
format (str) – The format that the decorated function will check.
raises (Exception) –
The exception(s) raised by the decorated function when an invalid instance is found.
The exception object will be accessible as the
jsonschema.exceptions.ValidationError.cause
attribute of the resulting validation error.
There are a number of default checkers that FormatChecker
s know how
to validate. Their names can be viewed by inspecting the
FormatChecker.checkers
attribute. Certain checkers will only be
available if an appropriate package is available for use. The easiest way to
ensure you have what is needed is to install jsonschema
using the
format
or format_nongpl
setuptools extra – i.e.
$ pip install jsonschema[format]
which will install all of the below dependencies for all formats.
Or if you want to install MIT-license compatible dependencies only:
$ pip install jsonschema[format_nongpl]
The non-GPL extra is intended to not install any direct dependencies
that are GPL (but that of course end-users should do their own verification).
At the moment, it supports all the available checkers except for iri
and
iri-reference
.
The more specific list of available checkers, along with their requirement (if any,) are listed below.
Note
If the following packages are not installed when using a checker that requires it, validation will succeed without throwing an error, as specified by the JSON Schema specification.
Checker |
Notes |
---|---|
|
requires webcolors |
|
|
|
requires strict-rfc3339 or rfc3339-validator |
|
|
|
|
|
requires idna |
|
|
|
OS must have |
|
requires rfc3987 |
|
requires rfc3987 |
|
requires jsonpointer |
|
|
|
requires jsonpointer |
|
requires strict-rfc3339 or rfc3339-validator |
|
requires rfc3987 or rfc3986-validator |
|
requires rfc3987 or rfc3986-validator |
Note
Since in most cases “validating” an email address is an attempt
instead to confirm that mail sent to it will deliver to a recipient,
and that that recipient is the correct one the email is intended
for, and since many valid email addresses are in many places
incorrectly rejected, and many invalid email addresses are in many
places incorrectly accepted, the email
format validator only
provides a sanity check, not full rfc5322 validation.
The same applies to the idn-email
format.