### Install fastjsonschema Source: https://horejsek.github.io/python-fastjsonschema/index.html Use pip to install the library. Requires Python 3.3 or higher. ```bash pip install fastjsonschema ``` -------------------------------- ### Compile JSON Schema with Default Values Source: https://horejsek.github.io/python-fastjsonschema/index.html Demonstrates how to use the `default` keyword in a JSON schema. When `use_default=True` (the default), missing properties with a default value will be populated. ```python validate = fastjsonschema.compile({ 'type': 'object', 'properties': { 'a': {'type': 'number', 'default': 42}, }, }) data = validate({}) assert data == {'a': 42} ``` -------------------------------- ### Run performance benchmarks Source: https://horejsek.github.io/python-fastjsonschema/index.html Execute the included performance benchmark script to compare validation speeds. ```bash $ make performance fast_compiled valid ==> 0.0993900 fast_compiled invalid ==> 0.0041089 fast_compiled_without_exc valid ==> 0.0465258 fast_compiled_without_exc invalid ==> 0.0023688 fast_file valid ==> 0.0989483 fast_file invalid ==> 0.0041104 fast_not_compiled valid ==> 11.9572681 fast_not_compiled invalid ==> 2.9512092 jsonschema valid ==> 5.2233240 jsonschema invalid ==> 1.3227916 jsonschema_compiled valid ==> 0.4447982 jsonschema_compiled invalid ==> 0.0231333 jsonspec valid ==> 4.1450569 jsonspec invalid ==> 1.0485777 validictory valid ==> 0.2730411 validictory invalid ==> 0.0183669 ``` -------------------------------- ### Compile JSON Schema with Custom Handlers and Formats Source: https://horejsek.github.io/python-fastjsonschema/index.html Shows how to provide custom handlers for remote schemas and custom format validators. Formats can be defined using regular expressions or callback functions. ```python validate = fastjsonschema.compile(definition, formats={ 'foo': r'foo|bar', 'bar': lambda value: value in ('foo', 'bar'), }) ``` -------------------------------- ### Generate Validation Code using Command Line Source: https://horejsek.github.io/python-fastjsonschema/index.html The `fastjsonschema` module can be used directly from the command line to generate validation code. The schema can be piped in or provided as an argument. ```bash echo "{'type': 'string'}" | python3 -m fastjsonschema > your_file.py ``` ```bash python3 -m fastjsonschema "{'type': 'string'}" > your_file.py ``` -------------------------------- ### Compile JSON Schema with Draft Version Source: https://horejsek.github.io/python-fastjsonschema/index.html Specifies the JSON schema draft version to use by including the `$schema` keyword in the definition. If not specified, the latest draft (draft-07) is used. ```python validate = fastjsonschema.compile({ '$schema': 'http://json-schema.org/draft-04/schema', 'type': 'number', }) ``` -------------------------------- ### Validate JSON with a compiled schema Source: https://horejsek.github.io/python-fastjsonschema/index.html Define a schema, compile it using fastjsonschema.compile, and use the resulting validator function to check data. ```python import fastjsonschema point_schema = { "type": "object", "properties": { "x": { "type": "number", }, "y": { "type": "number", }, }, "required": ["x", "y"], "additionalProperties": False, } point_validator = fastjsonschema.compile(point_schema) try: point_validator({"x": 1.0, "y": 2.0}) except fastjsonschema.JsonSchemaException as e: print(f"Data failed validation: {e}") ``` -------------------------------- ### Define fastjsonschema exceptions Source: https://horejsek.github.io/python-fastjsonschema/modules/fastjsonschema/exceptions.html The module provides base and specific exception classes for validation and definition errors. ```python import re SPLIT_RE = re.compile(r'[\.[\]]+') [docs]class JsonSchemaException(ValueError): """ Base exception of ``fastjsonschema`` library. """ [docs]class JsonSchemaValueException(JsonSchemaException): """ Exception raised by validation function. Available properties: * ``message`` containing human-readable information what is wrong (e.g. ``data.property[index] must be smaller than or equal to 42``), * invalid ``value`` (e.g. ``60``), * ``name`` of a path in the data structure (e.g. ``data.property[index]``), * ``path`` as an array in the data structure (e.g. ``['data', 'property', 'index']``), * the whole ``definition`` which the ``value`` has to fulfil (e.g. ``{'type': 'number', 'maximum': 42}``), * ``rule`` which the ``value`` is breaking (e.g. ``maximum``) * and ``rule_definition`` (e.g. ``42``). .. versionchanged:: 2.14.0 Added all extra properties. """ def __init__(self, message, value=None, name=None, definition=None, rule=None): super().__init__(message) self.message = message self.value = value self.name = name self.definition = definition self.rule = rule @property def path(self): return [item for item in SPLIT_RE.split(self.name) if item != ''] @property def rule_definition(self): if not self.rule or not self.definition: return None return self.definition.get(self.rule) [docs]class JsonSchemaDefinitionException(JsonSchemaException): """ Exception raised by generator of validation function. """ ``` -------------------------------- ### Internal Helper Functions Source: https://horejsek.github.io/python-fastjsonschema/modules/fastjsonschema.html Internal functions used by the library for schema processing and code generation. ```APIDOC ## Internal Helper Functions ### _factory Function #### Description Creates a `RefResolver` and a `CodeGenerator` instance based on the provided schema definition and options. #### Parameters - **definition** (dict) - The JSON schema definition. - **handlers** (dict) - Optional. Custom handlers for schema keywords. - **formats** (dict) - Optional. Custom formats for schema validation. - **use_default** (bool) - Optional. Whether to use default values. Defaults to True. - **use_formats** (bool) - Optional. Whether to use custom formats. Defaults to True. - **detailed_exceptions** (bool) - Optional. Whether to raise detailed exceptions. Defaults to True. #### Returns - **resolver** (RefResolver) - The configured reference resolver. - **code_generator** (CodeGenerator) - The code generator instance. ### _get_code_generator_class Function #### Description Determines and returns the appropriate `CodeGenerator` class based on the JSON schema version specified in the definition. #### Parameters - **schema** (dict) - The JSON schema definition, which may contain a '$schema' keyword. #### Returns - **CodeGeneratorDraft04** or **CodeGeneratorDraft06** or **CodeGeneratorDraft07** - The class for generating code specific to the schema draft version. ``` -------------------------------- ### fastjsonschema.compile Source: https://horejsek.github.io/python-fastjsonschema/sources/index.rst.txt Compiles a JSON schema into a Python function for faster repeated validation. ```APIDOC ## compile(definition) ### Description Compiles a JSON schema definition into a callable function that validates data against the schema. ### Parameters - **definition** (dict) - Required - The JSON schema definition. ### Response - **Returns** (callable) - A function that accepts data as an argument and returns the data if valid, or raises an exception. ``` -------------------------------- ### fastjsonschema.compile_to_code Source: https://horejsek.github.io/python-fastjsonschema/index.html Generates Python source code for a validation function based on the provided JSON schema. ```APIDOC ## fastjsonschema.compile_to_code ### Description Generates validation code for validating JSON schema passed in definition. ### Parameters - **definition** (dict) - Required - The JSON schema definition. - **handlers** (dict) - Optional - Mapping from URI to function for retrieving remote schemas. - **formats** (dict) - Optional - Mapping for custom formats. - **use_default** (bool) - Optional - Whether to support the 'default' keyword (default: True). - **use_formats** (bool) - Optional - Whether to use formats as assertions (default: True). - **detailed_exceptions** (bool) - Optional - Whether to provide detailed exception information (default: True). ### Request Example ```python import fastjsonschema code = fastjsonschema.compile_to_code({'type': 'string'}) with open('your_file.py', 'w') as f: f.write(code) ``` ``` -------------------------------- ### fastjsonschema.validate Source: https://horejsek.github.io/python-fastjsonschema/index.html Directly validates data against a schema without explicit compilation. ```APIDOC ## fastjsonschema.validate ### Description Validation function for use cases when you need to call validation only once. ### Parameters - **definition** (dict) - Required - The JSON schema definition. - **data** (any) - Required - The data to validate. - **handlers** (dict) - Optional - Mapping from URI to function for retrieving remote schemas. - **formats** (dict) - Optional - Mapping for custom formats. - **use_default** (bool) - Optional - Whether to support the 'default' keyword (default: True). - **use_formats** (bool) - Optional - Whether to use formats as assertions (default: True). - **detailed_exceptions** (bool) - Optional - Whether to provide detailed exception information (default: True). ### Request Example ```python import fastjsonschema fastjsonschema.validate({'type': 'string'}, 'hello') ``` ``` -------------------------------- ### Generate Python Code from JSON Schema Source: https://horejsek.github.io/python-fastjsonschema/index.html Use `fastjsonschema.compile_to_code` to generate a Python string containing the validation code for a given JSON schema. This code can then be written to a file. ```python import fastjsonschema code = fastjsonschema.compile_to_code({'type': 'string'}) with open('your_file.py', 'w') as f: f.write(code) ``` -------------------------------- ### compile_to_code Function Source: https://horejsek.github.io/python-fastjsonschema/modules/fastjsonschema.html Generates Python validation code from a JSON schema definition. This function can be used programmatically or as a command-line script. ```APIDOC ## compile_to_code Function ### Description Generates validation code for validating JSON schema passed in ``definition``. ### Parameters - **definition** (dict) - The JSON schema definition. - **handlers** (dict) - Optional. Custom handlers for schema keywords. - **formats** (dict) - Optional. Custom formats for schema validation. - **use_default** (bool) - Optional. Whether to use default values defined in the schema. Defaults to True. - **use_formats** (bool) - Optional. Whether to use custom formats. Defaults to True. - **detailed_exceptions** (bool) - Optional. Whether to raise detailed exceptions. Defaults to True. ### Request Example ```python import fastjsonschema code = fastjsonschema.compile_to_code({'type': 'string'}) with open('your_file.py', 'w') as f: f.write(code) ``` ### Script Usage Example ```bash # Using stdin echo "{'type': 'string'}" | python3 -m fastjsonschema > your_file.py # Using command-line argument python3 -m fastjsonschema "{'type': 'string'}" > your_file.py ``` ### Exception - **JsonSchemaDefinitionException** - Raised when generating the code fails due to a bad definition. ``` -------------------------------- ### fastjsonschema.validate Source: https://horejsek.github.io/python-fastjsonschema/sources/index.rst.txt Validates a JSON document against a provided schema. Raises an exception if validation fails. ```APIDOC ## validate(definition, data) ### Description Validates the provided data against the given JSON schema definition. ### Parameters - **definition** (dict) - Required - The JSON schema definition. - **data** (any) - Required - The data to be validated. ### Response - **Returns** (None) - Returns None if validation is successful. - **Raises** (JsonSchemaException) - Raised if the data does not conform to the schema. ``` -------------------------------- ### Compile JSON Schema to Validation Function Source: https://horejsek.github.io/python-fastjsonschema/index.html Use `fastjsonschema.compile` to generate a Python function that validates data against a given JSON schema. This is recommended for performance when validating multiple data instances. ```python import fastjsonschema validate = fastjsonschema.compile({'type': 'string'}) validate('hello') ``` -------------------------------- ### Validate Data Directly with JSON Schema Source: https://horejsek.github.io/python-fastjsonschema/index.html The `fastjsonschema.validate` function provides a simple way to validate data against a schema without explicitly compiling it first. This is suitable for single-use validations where performance is not critical. ```python import fastjsonschema fastjsonschema.validate({'type': 'string'}, 'hello') # same as: compile({'type': 'string'})('hello') ``` -------------------------------- ### fastjsonschema.compile Source: https://horejsek.github.io/python-fastjsonschema/modules/fastjsonschema.html Generates a validation function for a given JSON schema definition. ```APIDOC ## compile(definition, handlers={}, formats={}, use_default=True, use_formats=True, detailed_exceptions=True) ### Description Generates a highly optimized validation function for the provided JSON schema definition. ### Parameters - **definition** (dict) - Required - The JSON schema definition. - **handlers** (dict) - Optional - Mapping from URI to retrieval functions for remote schemas. - **formats** (dict) - Optional - Mapping for custom format validation. - **use_default** (bool) - Optional - Whether to apply default values defined in the schema. - **use_formats** (bool) - Optional - Whether to validate formats. - **detailed_exceptions** (bool) - Optional - Whether to provide detailed exception messages. ### Request Example ```python validate = fastjsonschema.compile({'type': 'string'}) validate('hello') ``` ``` -------------------------------- ### fastjsonschema.compile Source: https://horejsek.github.io/python-fastjsonschema/index.html Generates a validation function for a given JSON schema definition. ```APIDOC ## fastjsonschema.compile ### Description Generates a validation function for validating JSON schema passed in definition. ### Parameters - **definition** (dict) - Required - The JSON schema definition. - **handlers** (dict) - Optional - Mapping from URI to function for retrieving remote schemas. - **formats** (dict) - Optional - Mapping for custom formats. - **use_default** (bool) - Optional - Whether to support the 'default' keyword (default: True). - **use_formats** (bool) - Optional - Whether to use formats as assertions (default: True). - **detailed_exceptions** (bool) - Optional - Whether to provide detailed exception information (default: True). ### Request Example ```python import fastjsonschema validate = fastjsonschema.compile({'type': 'string'}) validate('hello') ``` ``` -------------------------------- ### fastjsonschema.validate Source: https://horejsek.github.io/python-fastjsonschema/modules/fastjsonschema.html Validates data against a provided JSON schema definition. ```APIDOC ## validate(definition, data) ### Description Validates the provided data against the given JSON schema definition. ### Parameters - **definition** (dict) - Required - The JSON schema definition. - **data** (any) - Required - The data to validate. ### Request Example ```python import fastjsonschema fastjsonschema.validate({'type': 'string'}, 'hello') ``` ``` -------------------------------- ### fastjsonschema.validate Source: https://horejsek.github.io/python-fastjsonschema/modules/fastjsonschema.html Validates a JSON document against a schema definition without requiring manual compilation. Suitable for one-off validation tasks. ```APIDOC ## validate(definition, data, handlers={}, formats={}, use_default=True, use_formats=True, detailed_exceptions=True) ### Description Validates a JSON document against a provided schema definition. This function is designed for scenarios where the schema is used only once, avoiding the overhead of manual compilation. ### Parameters - **definition** (dict) - Required - The JSON schema definition. - **data** (any) - Required - The JSON document to validate. - **handlers** (dict) - Optional - Dictionary of URI handlers for $ref resolution. - **formats** (dict) - Optional - Dictionary of custom format validators. - **use_default** (bool) - Optional - Whether to apply default values defined in the schema. - **use_formats** (bool) - Optional - Whether to enable format validation. - **detailed_exceptions** (bool) - Optional - Whether to raise detailed exception messages. ### Response - **Returns** (any) - Returns the validated data (potentially transformed if defaults are applied). - **Raises** (JsonSchemaException) - Raised if the data fails validation. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.