### Install jsonschema using pip Source: https://github.com/python-jsonschema/jsonschema/blob/main/README.rst Install the jsonschema library using pip. This command installs the base package. ```bash pip install jsonschema ``` -------------------------------- ### Install jsonschema with format validation extras Source: https://github.com/python-jsonschema/jsonschema/blob/main/README.rst Install the jsonschema library with the 'format' extra dependencies to enable additional format validation capabilities. ```bash pip install jsonschema'[format]' ``` -------------------------------- ### Example Remote References JSON Source: https://github.com/python-jsonschema/jsonschema/blob/main/json/README.md An example of the JSON output from `bin/jsonschema_suite remotes`, showing URIs and their associated schema definitions. This is used to configure implementations for resolving remote references. ```json { "http://localhost:1234/baseUriChange/folderInteger.json": { "type": "integer" }, "http://localhost:1234/baseUriChangeFolder/folderInteger.json": { "type": "integer" } } ``` -------------------------------- ### Configure Registry for File System Resolution Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/referencing.rst Set up a `Registry` to dynamically retrieve schemas from the file system. This `retrieve_from_filesystem` function maps URIs starting with `http://localhost/` to files within the `/tmp/schemas` directory. ```python from pathlib import Path import json from referencing import Registry, Resource from referencing.exceptions import NoSuchResource SCHEMAS = Path("/tmp/schemas") def retrieve_from_filesystem(uri: str): if not uri.startswith("http://localhost/"): raise NoSuchResource(ref=uri) path = SCHEMAS / Path(uri.removeprefix("http://localhost/")) contents = json.loads(path.read_text()) return Resource.from_contents(contents) registry = Registry(retrieve=retrieve_from_filesystem) ``` -------------------------------- ### Validating Formats Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/validate.rst Explains how to use the `format` keyword and `FormatChecker` to validate primitive types against predefined formats. It also covers installing optional dependencies. ```APIDOC ## Validating Formats JSON Schema defines the `:kw:`format` keyword which can be used to check if primitive types (``string``\s, ``number``\s, ``boolean``\s) conform to well-defined formats. By default, as per the specification, no validation is enforced. Optionally however, validation can be enabled by hooking a `format-checking object ` into a `Validator`. ### Installation Some formats require additional dependencies. Install `jsonschema` with extras: ```sh $ pip install jsonschema[format] ``` Or to avoid GPL dependencies: ```sh $ pip install jsonschema[format-nongpl] ``` ### Format Table | Checker | Notes | |---|---| | ``color`` | requires webcolors_ | | ``date`` | | ``date-time`` | requires rfc3339-validator_ | | ``duration`` | requires isoduration_ | | ``email`` | | ``hostname`` | requires fqdn_ | | ``idn-hostname`` | requires idna_ | | ``ipv4`` | | ``ipv6`` | OS must have `socket.inet_pton` function | | ``iri`` | requires rfc3987_ or rfc3987-syntax_ | | ``iri-reference`` | requires rfc3987_ or rfc3987-syntax_ | | ``json-pointer`` | requires jsonpointer_ | | ``regex`` | | ``relative-json-pointer`` | requires jsonpointer_ | | ``time`` | requires rfc3339-validator_ | | ``uri`` | requires rfc3987_ or rfc3986-validator_ | | ``uri-reference`` | requires rfc3987_ or rfc3986-validator_ | | ``uri-template`` | requires uri-template_ | | ``uuid`` | _fqdn: https://pypi.org/pypi/fqdn/ _idna: https://pypi.org/pypi/idna/ _isoduration: https://pypi.org/pypi/isoduration/ _jsonpointer: https://pypi.org/pypi/jsonpointer/ _rfc3339-validator: https://pypi.org/project/rfc3339-validator/ _rfc3986-validator: https://pypi.org/project/rfc3986-validator/ _rfc3987: https://pypi.org/pypi/rfc3987/ _rfc3987-syntax: https://pypi.org/pypi/rfc3987-syntax/ _uri-template: https://pypi.org/pypi/uri-template/ _webcolors: https://pypi.org/pypi/webcolors/ ### FormatChecker Class .. autoclass:: FormatChecker :members: :noindex: :exclude-members: cls_checks .. attribute:: 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` decorator. .. 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. :argument str format: the format that the decorated function will check :argument Exception raises: the exception(s) raised ### Example: Using Format Checker ```python from jsonschema import validate, Draft202012Validator # Example of successful validation validate("127.0.0.1", {"format" : "ipv4"}) # Example of failed validation with format checker validate( instance="-12", schema={"format" : "ipv4"}, format_checker=Draft202012Validator.FORMAT_CHECKER, ) # Expected output: ValidationError: "-12" is not a "ipv4" ``` ``` -------------------------------- ### Example: Validating a Schema against Meta-Schema Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/validate.rst Demonstrates how to use a validator class to check if a schema conforms to its corresponding meta-schema. ```APIDOC ## Example: Validating a Schema against Meta-Schema ```python from jsonschema import Draft202012Validator schema = { "$schema": Draft202012Validator.META_SCHEMA["$id"], "type": "object", "properties": { "name": {"type": "string"}, "email": {"type": "string"}, }, "required": ["email"] } Draft202012Validator.check_schema(schema) ``` ``` -------------------------------- ### Combine In-Memory and File System Schemas Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/referencing.rst Create a registry that includes both in-memory schemas and file system resolution capabilities. This example adds a specific schema for non-empty arrays using `DRAFT7` alongside the file system retriever. ```python from referencing.jsonschema import DRAFT7 registry = Registry(retrieve=retrieve_from_filesystem).with_resource( "urn:non-empty-array", DRAFT7.create_resource({"type": "array", "minItems": 1}), ) ``` -------------------------------- ### Validate Instance Against Schema Store Schema Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/referencing.rst Demonstrates validating an instance against a schema from the JSON Schema Store using a registry configured for HTTP retrieval. This example shows how to pass the custom registry to the Validator. ```python from jsonschema import Draft202012Validator Draft202012Validator( {"$ref": "https://www.schemastore.org/json/pyproject.json"}, registry=registry, ).validate({"project": {"name": 12}}) ``` -------------------------------- ### Example Usage of Validation Errors Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/errors.rst Demonstrates how to iterate through validation errors and access their messages. ```APIDOC ## Example: Handling Validation Errors ### Description This example shows how to use `iter_errors` to get validation errors and print their messages. ### Method `Draft202012Validator.iter_errors(instance) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python schema = { "items": { "anyOf": [ {"type": "string", "maxLength": 2}, {"type": "integer", "minimum": 5} ] } } instance = [{}, 3, "foo"] v = Draft202012Validator(schema) errors = sorted(v.iter_errors(instance), key=lambda e: e.path) for error in errors: print(error.message) ``` ### Response #### Success Response (200) None (This is a code example, not an API endpoint) #### Response Example ```text {} is not valid under any of the given schemas 3 is not valid under any of the given schemas ``` ``` -------------------------------- ### Validate Instance with Format Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/validate.rst Use the `validate` function with a schema that includes a 'format' keyword to validate an instance. Optionally, provide a `format_checker` to enable format validation. This example shows validation for 'ipv4' format. ```python >>> validate("127.0.0.1", {"format" : "ipv4"}) >>> validate( ... instance="-12", ... schema={"format" : "ipv4"}, ... format_checker=Draft202012Validator.FORMAT_CHECKER, ... ) Traceback (most recent call last): ... ValidationError: "-12" is not a "ipv4" ``` -------------------------------- ### Applying Defaults to Nested Objects Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/faq.rst This example demonstrates how to apply default values to nested objects. It requires providing a default empty object for the parent property to ensure it's instantiated before its properties can receive defaults. ```python schema = { "type": "object", "properties": { "outer-object": { "type": "object", "properties" : { "inner-object": { "type": "string", "default": "INNER-DEFAULT" } }, "default": {} } } } obj = {} DefaultValidatingValidator(schema).validate(obj) assert obj == {'outer-object': {'inner-object': 'INNER-DEFAULT'}} ``` -------------------------------- ### Retrieve YAML Documents with PyYAML Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/referencing.rst Configure a registry to retrieve YAML documents by providing a custom retrieve function that uses PyYAML to load content from local files. Ensure URIs start with 'http://localhost/' to be handled. ```python from pathlib import Path import yaml from referencing import Registry, Resource from referencing.exceptions import NoSuchResource SCHEMAS = Path("/tmp/yaml-schemas") def retrieve_yaml(uri: str): if not uri.startswith("http://localhost/"): raise NoSuchResource(ref=uri) path = SCHEMAS / Path(uri.removeprefix("http://localhost/")) contents = yaml.safe_load(path.read_text()) return Resource.from_contents(contents) registry = Registry(retrieve=retrieve_yaml) ``` -------------------------------- ### JSON Schema with Format Validation Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/faq.rst A JSON schema example specifying a string type with the 'date' format. Note that format validation is not enabled by default in older drafts and requires explicit configuration. ```json {"type": "string", "format": "date"} ``` -------------------------------- ### Default Object Not Instantiated Without Default Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/faq.rst This example shows that if a parent object property does not have a 'default' value defined in the schema, it will not be instantiated, and consequently, its nested properties will not receive their defaults. ```python del schema["properties"]["outer-object"]["default"] obj2 = {} DefaultValidatingValidator(schema).validate(obj2) assert obj2 == {} # whoops ``` -------------------------------- ### Validate JSON with a Custom Registry Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/referencing.rst Pass a custom registry to the `Validator` to enable it to resolve references defined within schemas. This example validates an object against a schema that uses a URN reference. ```python from jsonschema import Draft202012Validator validator = Draft202012Validator( { "type": "object", "additionalProperties": {"$ref": "urn:nonneg-integer-schema"}, }, registry=registry, # the critical argument, our registry from above ) validator.validate({"foo": 37}) assert not validator.is_valid({"foo": -37}) # Uh oh! ``` -------------------------------- ### Extend Validator with Custom Type Checking Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/validate.rst This example demonstrates how to extend a validator to include custom type checking. It redefines the 'number' type to accept instances of a custom 'MyInteger' class in addition to standard numbers. This is useful for adding specific type validations beyond the defaults. ```python from jsonschema import validators class MyInteger: pass def is_my_int(checker, instance): return ( Draft202012Validator.TYPE_CHECKER.is_type(instance, "number") or isinstance(instance, MyInteger) ) type_checker = Draft202012Validator.TYPE_CHECKER.redefine( "number", is_my_int, ) CustomValidator = validators.extend( Draft202012Validator, type_checker=type_checker, ) validator = CustomValidator(schema={"type" : "number"}) ``` -------------------------------- ### Create and Populate a Referencing Registry Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/referencing.rst Demonstrates creating a referencing.Registry and adding a schema resource identified by a URI. The Registry object is immutable; methods that modify it return new instances. ```python from referencing import Registry, Resource from referencing.jsonschema import DRAFT202012 schema = Resource(contents={"type": "integer"}, specification=DRAFT202012) registry = Registry().with_resource(uri="http://example.com/my/schema", resource=schema) print(registry) ``` -------------------------------- ### Migrate Schema Store from _RefResolver to referencing.Registry Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/referencing.rst Demonstrates how to migrate schema storage from _RefResolver's 'store' argument to referencing.Registry's 'with_resource' method. This is useful when you previously passed a set of schemas to the resolver. ```python from jsonschema import Draft202012Validator, RefResolver resolver = RefResolver.from_schema( schema={"title": "my schema"}, store={"http://example.com": {"type": "integer"}}, ) validator = Draft202012Validator( {"$ref": "http://example.com"}, resolver=resolver, ) validator.validate("foo") ``` ```python from referencing import Registry from referencing.jsonschema import DRAFT202012 from jsonschema import Draft202012Validator registry = Registry().with_resource( "http://example.com", DRAFT202012.create_resource({"type": "integer"}), ) validator = Draft202012Validator( {"$ref": "http://example.com"}, registry=registry, ) assert not validator.is_valid("foo") ``` -------------------------------- ### Create Schema Resource from Contents Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/referencing.rst Use `Resource.from_contents` to create a schema resource. It inspects the `$schema` keyword to determine the schema dialect. ```python from referencing import Registry, Resource schema = Resource.from_contents( { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "integer", "minimum": 0, }, ) registry = Registry().with_resources( [ ("http://example.com/nonneg-int-schema", schema), ("urn:nonneg-integer-schema", schema), ], ) ``` -------------------------------- ### Retrieve Resources Over HTTP with httpx Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/referencing.rst Set up a registry to automatically fetch schemas from the JSON Schema Store over HTTP using the httpx library. This function parses the response JSON and creates a Resource. ```python from referencing import Registry, Resource import httpx def retrieve_via_httpx(uri: str): response = httpx.get(uri) return Resource.from_contents(response.json()) registry = Registry(retrieve=retrieve_via_httpx) ``` -------------------------------- ### Implement Custom Retrieve Function for referencing.Registry Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/referencing.rst Shows how to create a custom 'retrieve' function for referencing.Registry to handle custom URI schemes like 'file' or 'custom'. This replaces the 'handlers' functionality of _RefResolver. ```python from urllib.parse import urlsplit def retrieve(uri: str): parsed = urlsplit(uri) if parsed.scheme == "file": ... elif parsed.scheme == "custom": ... registry = Registry(retrieve=retrieve) ``` -------------------------------- ### Sample Test Case Structure Source: https://github.com/python-jsonschema/jsonschema/blob/main/json/README.md Illustrates the structure of a single test case, which includes a schema, a description, and an array of tests. Each test contains its own description, data, and a validity flag. ```json { "description": "The test case description", "schema": { "type": "string" }, "tests": [ { "description": "a test with a valid instance", "data": "a string", "valid": true }, { "description": "a test with an invalid instance", "data": 15, "valid": false } ] } ``` -------------------------------- ### Ambiguous Basic Output Structure (2019-09/2020-12) Source: https://github.com/python-jsonschema/jsonschema/blob/main/json/output-tests/README.md Illustrates two possible structures for the 'basic' output format when a list contains a single output node. This ambiguity is addressed by forcing a second output unit. ```json { "valid": false, "errors": [ { "valid": false, "keywordLocation": "", "absoluteKeywordLocation": "https://json-schema.org/tests/content/draft2019-09/general/0", "instanceLocation": "" } ] } ``` ```json { "valid": false, "keywordLocation": "", "absoluteKeywordLocation": "https://json-schema.org/tests/content/draft2019-09/general/0", "instanceLocation": "" } ``` -------------------------------- ### Submodules Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/api/index.rst Links to the API documentation for submodules within the jsonschema library. ```APIDOC ## Submodules ### Description This section provides links to the API documentation for the various submodules of the jsonschema library. ### Submodule Documentation - `/api/jsonschema/validators/index` - `/api/jsonschema/exceptions/index` - `/api/jsonschema/protocols/index` ``` -------------------------------- ### Create Schema Resource with Specific Dialect Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/referencing.rst Use a dialect like `DRAFT202012` to create a schema resource when the schema itself doesn't specify a `$schema` identifier. This ensures consistent interpretation. ```python from referencing import Registry, Resource from referencing.jsonschema import DRAFT202012 schema = DRAFT202012.create_resource({"type": "integer", "minimum": 0}) registry = Registry().with_resources( [ ("http://example.com/nonneg-int-schema", schema), ("urn:nonneg-integer-schema", schema), ], ) ``` -------------------------------- ### Retrieve Schema Contents from Registry Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/referencing.rst Shows how to access the contents of a schema resource stored in a referencing.Registry using its URI. ```python print(registry.contents("http://example.com/my/schema")) ``` -------------------------------- ### Iterating Over Validation Errors Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/errors.rst Demonstrates how to validate an instance against a schema and iterate over the sorted validation errors. This is useful for collecting and analyzing all validation issues. ```python schema = { "items": { "anyOf": [ {"type": "string", "maxLength": 2}, {"type": "integer", "minimum": 5} ] } } instance = [{}, 3, "foo"] v = Draft202012Validator(schema) errors = sorted(v.iter_errors(instance), key=lambda e: e.path) ``` -------------------------------- ### Error Tree Navigation and Access Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/errors.rst Demonstrates how to access validation errors within an error tree structure. ```APIDOC ## Error Tree Navigation and Access ### Description Error trees in `jsonschema` allow for hierarchical access to validation errors. Each node in the tree represents a part of the instance being validated, and child trees can be accessed by indexing. ### Method N/A (Conceptual usage) ### Endpoint N/A (Internal library feature) ### Parameters N/A ### Request Example N/A ### Response #### Success Response (Conceptual) - **errors** (dict) - A dictionary mapping validation keywords to their corresponding errors. #### Response Example ```python # Assuming 'tree' is an ErrorTree object if "minItems" in tree.errors: print("minItems validation failed") # Accessing child errors child_tree = tree[index] ``` ``` -------------------------------- ### Print Detailed Error Message Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/errors.rst View a comprehensive string representation of a validation error, including the failure reason and relevant schema/instance details. ```python print(errors[1]) ``` -------------------------------- ### Execute jsonschema Suite Remotes Source: https://github.com/python-jsonschema/jsonschema/blob/main/json/README.md This command retrieves all remote references for the jsonschema test suite. It outputs a JSON object mapping URIs to their corresponding schema content. ```bash $ bin/jsonschema_suite remotes ``` -------------------------------- ### Schema Validation Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/validate.rst The simplest way to validate an instance under a given schema is to use the `validate` function. ```APIDOC ## Schema Validation ### Description Validates a JSON instance against a given JSON schema. ### Method `validate` function from the `jsonschema` library. ### Endpoint N/A (Python function) ### Parameters N/A ### Request Example ```python from jsonschema import validate schema = { "type": "object", "properties": { "name": {"type": "string"}, "age": {"type": "integer"} } } instance = {"name": "John Doe", "age": 30} validate(instance=instance, schema=schema) ``` ### Response #### Success Response (200) No explicit return value on success; raises `ValidationError` on failure. #### Response Example N/A (raises exceptions on error) ``` -------------------------------- ### Inspect Error Instance and Schema Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/errors.rst Examine the specific part of the instance and subschema that caused an error using `ValidationError.instance` and `ValidationError.schema`. ```python for error in errors: for suberror in sorted(error.context, key=lambda e: e.schema_path): print(list(suberror.schema_path), suberror.message, sep=", ") ``` -------------------------------- ### Validator Creation Functions Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/creating.rst Functions for creating and extending validator classes. ```APIDOC ## Validator Creation Functions ### Description These functions are used to create new validator classes or extend existing ones. ### Functions - `create()`: Creates a new validator class. - `extend()`: Extends an existing validator class. - `validator_for()`: Returns a validator class for a given schema. - `validates()`: Decorator to associate a validator with a schema. ``` -------------------------------- ### jsonschema.exceptions Module API Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/api/jsonschema/exceptions/index.rst This snippet details the members and undocumented members of the jsonschema.exceptions module. ```APIDOC ## Module: jsonschema.exceptions ### Description This module contains all the exceptions that can be raised by the jsonschema library. ### Members - **members**: All public members of the module are documented. - **undoc-members**: All members of the module are documented, including those that are not explicitly documented. ### Usage Import specific exceptions or the entire module to handle validation errors. ```python from jsonschema.exceptions import ValidationError, SchemaError try: # Code that might raise a validation error pass except ValidationError as e: print(f"Validation Error: {e.message}") except SchemaError as e: print(f"Schema Error: {e.message}") ``` ``` -------------------------------- ### jsonschema Module Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/api/index.rst Core functionalities and data exposed by the jsonschema module. ```APIDOC ## jsonschema Module ### Description Provides access to core functionalities and data within the jsonschema library. ### Members - `jsonschema._format._F` (autodata) - `jsonschema._typing.id_of` (autodata) ### Excluded Members - `FormatError` - `Validator` - `ValidationError` ``` -------------------------------- ### JSON Test Case Structure Source: https://github.com/python-jsonschema/jsonschema/blob/main/json/README.md This JSON structure represents a test case within the JSON Schema Test Suite. It includes a description, the schema to be tested, and a list of tests, each with its own description, data, and expected validity. ```json { "description": "Test the \"type\" schema keyword", "schema": { "$ref": "https://json-schema.org/draft/2019-09/schema" }, "tests": [ { "description": "Valid: string", "data": { "type": "string" }, "valid": true }, { "description": "Invalid: null", "data": { "type": null }, "valid": false } ] } ``` -------------------------------- ### The Validator Protocol Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/creating.rst Information about the jsonschema.protocols.Validator protocol. ```APIDOC ## The Validator Protocol ### Description The `jsonschema.protocols.Validator` is a `typing.Protocol` that describes the type of a validator. It can be used in type annotations. ### Details For full details, refer to the `validator-protocol` documentation. ``` -------------------------------- ### Check for Errors at Instance Index using ErrorTree Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/errors.rst Use the `in` operator with an `ErrorTree` to check if a specific index in the instance has associated validation errors. ```python >>> 0 in tree True >>> 1 in tree False ``` -------------------------------- ### Validate JSON Instance Against Schema Source: https://github.com/python-jsonschema/jsonschema/blob/main/README.rst Use the `validate` function to check if a JSON instance conforms to a given schema. If the instance is invalid, a `ValidationError` is raised. ```python from jsonschema import validate # A sample schema, like what we'd get from json.load() schema = { "type" : "object", "properties" : { "price" : {"type" : "number"}, "name" : {"type" : "string"}, }, } # If no exception is raised by validate(), the instance is valid. validate(instance={"name" : "Eggs", "price" : 34.99}, schema=schema) validate( instance={"name" : "Eggs", "price" : "Invalid"}, schema=schema, ) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... ValidationError: 'Invalid' is not of type 'number' ``` -------------------------------- ### Creating Validation Errors Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/creating.rst Guidelines for creating validation errors within custom validators. ```APIDOC ## Creating Validation Errors ### Description When validating against a subschema, use `descend` instead of `iter_errors`. If recursing into the instance or schema, provide `path` or `schema_path` arguments to `descend` to correctly track error locations. ### Method - Call `descend` for subschema validation. - Pass `path` and/or `schema_path` to `descend` when recursing. ``` -------------------------------- ### Printing Validation Error Messages Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/errors.rst Shows how to print the human-readable message for each validation error found. This is a common way to display errors to users or in logs. ```python for error in errors: print(error.message) ``` -------------------------------- ### Create an ErrorTree from Validation Errors Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/errors.rst Construct an `ErrorTree` object from an iterable of `ValidationError` objects for easier programmatic querying of errors. ```python from jsonschema.exceptions import ErrorTree tree = ErrorTree(v.iter_errors(instance)) ``` -------------------------------- ### Validate Schema Against Meta-Schema Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/validate.rst Use Draft202012Validator.check_schema to validate a schema against the Draft 2020-12 meta-schema. Ensure the schema includes the '$schema' keyword pointing to the meta-schema's ID. ```python from jsonschema import Draft202012Validator schema = { "$schema": Draft202012Validator.META_SCHEMA["$id"], "type": "object", "properties": { "name": {"type": "string"}, "email": {"type": "string"}, }, "required": ["email"] } Draft202012Validator.check_schema(schema) ``` -------------------------------- ### Query Errors by Validation Keyword using ErrorTree Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/errors.rst Access the `errors` attribute of an `ErrorTree` to see which validation keywords failed for a specific part of the instance. ```python >>> sorted(tree[0].errors) ['enum', 'type'] ``` -------------------------------- ### Iterate Validation Errors for an Array Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/errors.rst Iterate through validation errors for a given schema and instance, particularly useful for array types. ```python v = Draft202012Validator(schema) for error in sorted(v.iter_errors(["spam", 2]), key=str): print(error.message) ``` -------------------------------- ### Validator Protocol Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/validate.rst `jsonschema` defines a protocol that all validator classes adhere to, ensuring they have methods like `iter_errors`. ```APIDOC ## Validator Protocol ### Description Describes the interface that all validator classes in `jsonschema` must implement. This includes methods for iterating over validation errors. ### Method `jsonschema.protocols.Validator` (protocol definition) ### Endpoint N/A (Python protocol) ### Parameters N/A ### Request Example N/A ### Response N/A ### Members - `iter_errors(instance)`: Iterates over all validation errors for the given instance. - `is_valid(instance)`: Returns `True` if the instance is valid, `False` otherwise. - `validate(instance)`: Validates the instance, raising `ValidationError` if invalid. ``` -------------------------------- ### Iterate Through Validation Error Paths Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/errors.rst Access the path within the instance that corresponds to each validation error by iterating over `ValidationError.path`. ```python for error in errors: print(list(error.path)) ``` -------------------------------- ### Find the most relevant error with best_match Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/errors.rst Use the `best_match` function to identify the most relevant validation error from an iterable of errors. It requires importing `best_match` and a validator instance. ```python >>> from jsonschema import Draft202012Validator >>> from jsonschema.exceptions import best_match >>> schema = { ... "type": "array", ... "minItems": 3, ... } >>> print(best_match(Draft202012Validator(schema).iter_errors(11)).message) 11 is not of type 'array' ``` -------------------------------- ### Type Checking Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/validate.rst Validators use an associated `TypeChecker` to handle the JSON Schema `:kw:type` keyword. Defaults are suitable for most users. ```APIDOC ## Type Checking ### Description Manages the mapping between type names (e.g., "string", "number") and functions that test if an instance conforms to that type. Custom type checkers can be defined. ### Method `jsonschema.TypeChecker` ### Endpoint N/A (Python class) ### Parameters N/A ### Request Example ```python from jsonschema import validators # Example of redefining a type check class MyInteger: pass def is_my_int(checker, instance): return ( validators.Draft202012Validator.TYPE_CHECKER.is_type(instance, "number") or isinstance(instance, MyInteger) ) type_checker = validators.Draft202012Validator.TYPE_CHECKER.redefine( "number", is_my_int, ) CustomValidator = validators.extend( validators.Draft202012Validator, type_checker=type_checker, ) validator = CustomValidator(schema={"type" : "number"}) ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Sort errors by relevance using the relevance function Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/errors.rst Sort validation errors based on heuristic relevance using the `relevance` function as a key for sorting functions like `sorted`. This function prioritizes certain error types. ```python >>> schema = { ... "properties": { ... "name": {"type": "string"}, ... "phones": { ... "properties": { ... "home": {"type": "string"} ... }, ... }, ... }, ... } >>> instance = {"name": 123, "phones": {"home": [123]}} >>> errors = Draft202012Validator(schema).iter_errors(instance) >>> [ ... e.path[-1] ... for e in sorted(errors, key=exceptions.relevance) ... ] ['home', 'name'] ``` -------------------------------- ### jsonschema.validators Module Members Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/api/jsonschema/validators/index.rst This section lists all members, undocumented members, and private members of the jsonschema.validators module, with a focus on the _RefResolver class. ```APIDOC ## Module: jsonschema.validators ### Description Provides classes and functions for validating JSON data against a JSON schema. ### Members This module exposes various validators and related utilities. The `_RefResolver` class is a private member used for resolving references within schemas. ### Undocumented Members Includes members that may not have explicit documentation. ### Private Members - **_RefResolver** (`jsonschema.validators._RefResolver`): A private class used internally for resolving JSON references within schemas. It handles fetching and parsing schema documents from various locations. ### Usage Example (Conceptual) ```python from jsonschema import Draft7Validator schema = {"type": "object", "properties": {"name": {"type": "string"}}} validator = Draft7Validator(schema) instance = {"name": "John Doe"} validator.validate(instance) print("Instance is valid.") # Example of reference resolution (internal usage of _RefResolver) # This is typically handled by the validator itself. ``` ### Related Classes - `jsonschema.validators.Validator` - `jsonschema.validators.RefResolver` ``` -------------------------------- ### best_match Function Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/errors.rst Utility function to find the most relevant error from a collection of validation errors. ```APIDOC ## best_match Function ### Description The `best_match` function helps identify the most relevant validation error from an iterable of errors. It's useful when dealing with multiple potential validation failures. ### Method `best_match(errors)` ### Endpoint N/A (Internal library function) ### Parameters - **errors** (iterable) - An iterable of `ValidationError` objects. ### Request Example N/A ### Response #### Success Response (200) - **ValidationError** - The most relevant `ValidationError` object found. #### Response Example ```python from jsonschema import Draft202012Validator from jsonschema.exceptions import best_match schema = { "type": "array", "minItems": 3, } validator = Draft202012Validator(schema) errors = validator.iter_errors(11) most_relevant_error = best_match(errors) print(most_relevant_error.message) # Output: 11 is not of type 'array' ``` ``` -------------------------------- ### Versioned Validators Source: https://github.com/python-jsonschema/jsonschema/blob/main/docs/validate.rst `jsonschema` provides validator classes for various versions of the JSON Schema specification. ```APIDOC ## Versioned Validators ### Description Provides specific validator classes that conform to different versions of the JSON Schema specification (e.g., Draft202012Validator, Draft7Validator). ### Method Validator classes like `jsonschema.validators.Draft202012Validator`, `jsonschema.validators.Draft7Validator`, etc. ### Endpoint N/A (Python classes) ### Parameters N/A ### Request Example ```python from jsonschema import Draft7Validator schema = {"type": "integer"} instance = 10 validator = Draft7Validator(schema) print(validator.is_valid(instance)) ``` ### Response #### Success Response (200) N/A #### Response Example N/A ```