Top Related Projects
An implementation of the JSON Schema specification for Python
A PHP implementation of JSON Schema validation
Tiny Validator for JSON Schema v4
Quick Overview
The jsonschema
library is a Python implementation of JSON Schema, a vocabulary that allows you to annotate and validate JSON documents. It provides a flexible and powerful way to define and validate the structure and content of JSON data, making it a valuable tool for working with JSON-based APIs and data formats.
Pros
- Comprehensive Validation: The library supports a wide range of JSON Schema features, allowing you to define complex validation rules for your JSON data.
- Extensibility: The library can be extended with custom validation rules and formats, making it adaptable to your specific use cases.
- Detailed Error Reporting: When validation fails, the library provides detailed error messages that help you identify and fix issues in your JSON data.
- Compatibility: The library is compatible with a wide range of Python versions, from 2.7 to the latest 3.x releases.
Cons
- Performance: Depending on the complexity of your JSON Schema and the size of your data, the validation process can be computationally expensive, which may impact the performance of your application.
- Learning Curve: Mastering the JSON Schema specification and the library's API can have a steeper learning curve, especially for developers new to the concept of JSON Schema.
- Limited Tooling: While the library itself is well-documented, the ecosystem of tools and integrations around
jsonschema
may be less extensive compared to other validation libraries. - Dependency Management: The library has a relatively small number of dependencies, but you'll need to manage them carefully to avoid version conflicts in your project.
Code Examples
Here are a few examples of how to use the jsonschema
library:
- Validating a JSON document against a schema:
from jsonschema import validate
# Define the JSON schema
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer", "minimum": 0}
},
"required": ["name", "age"]
}
# Validate a JSON document against the schema
data = {"name": "John Doe", "age": 30}
validate(instance=data, schema=schema)
- Defining a custom validation rule:
from jsonschema import Draft7Validator, validators
def is_positive(validator, value, instance, schema):
if instance < 0:
yield {
"message": "Value must be positive",
"validator": "isPositive",
"value": instance
}
custom_validator = validators.extend(Draft7Validator, {"isPositive": is_positive})
schema = {"type": "integer", "isPositive": True}
custom_validator(schema).validate(-10)
- Validating nested JSON structures:
from jsonschema import validate
# Define the JSON schema
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"address": {
"type": "object",
"properties": {
"street": {"type": "string"},
"city": {"type": "string"},
"state": {"type": "string"}
},
"required": ["street", "city", "state"]
}
},
"required": ["name", "address"]
}
# Validate a JSON document against the schema
data = {
"name": "John Doe",
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA"
}
}
validate(instance=data, schema=schema)
Getting Started
To get started with the jsonschema
library, follow these steps:
- Install the library using pip:
pip install jsonschema
- Import the
validate
function from thejsonschema
module:
from jsonschema import validate
- Define your JSON schema using a Python dictionary:
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer", "minimum": 0}
},
"
Competitor Comparisons
An implementation of the JSON Schema specification for Python
Pros of python-jsonschema/jsonschema
- Comprehensive documentation and examples, making it easier to get started and understand the library.
- Actively maintained with regular updates and bug fixes.
- Supports a wide range of JSON Schema versions, including draft-04, draft-06, and draft-07.
Cons of python-jsonschema/jsonschema
- May have a steeper learning curve compared to other JSON validation libraries.
- Dependency on the
six
library, which may not be necessary for all projects. - Potential performance issues for large or complex JSON schemas.
Code Comparison
python-jsonschema/jsonschema
from jsonschema import validate
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"}
}
}
data = {"name": "John", "age": 30}
validate(instance=data, schema=schema)
python-jsonschema/jsonschema
from jsonschema import validate
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"}
}
}
data = {"name": "John", "age": "30"}
validate(instance=data, schema=schema) # Raises ValidationError
A PHP implementation of JSON Schema validation
Pros of json-schema
- Lightweight and focused on JSON Schema validation
- Simple API for easy integration into projects
- Supports multiple JSON Schema versions (draft-04, draft-06, draft-07)
Cons of json-schema
- Less actively maintained compared to jsonschema
- Fewer features and customization options
- Limited documentation and community support
Code Comparison
jsonschema:
from jsonschema import validate
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer", "minimum": 0}
}
}
validate(instance={"name": "John", "age": 30}, schema=schema)
json-schema:
from json_schema import validate
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer", "minimum": 0}
}
}
validate({"name": "John", "age": 30}, schema)
Summary
While json-schema offers a lightweight and straightforward approach to JSON Schema validation, jsonschema provides a more comprehensive and actively maintained solution. jsonschema offers more features, better documentation, and wider community support, making it a preferred choice for most projects. However, json-schema may be suitable for simpler use cases or projects with minimal requirements.
Tiny Validator for JSON Schema v4
Pros of tv4
- Lightweight and fast JSON Schema validator
- Supports both browser and Node.js environments
- Simple API with synchronous validation
Cons of tv4
- Limited support for newer JSON Schema versions
- Less active development and maintenance
- Fewer advanced features compared to jsonschema
Code Comparison
tv4:
var valid = tv4.validate(data, schema);
if (valid) {
console.log('Valid');
} else {
console.log(tv4.error);
}
jsonschema:
from jsonschema import validate
try:
validate(instance=data, schema=schema)
print("Valid")
except ValidationError as ve:
print(ve)
Key Differences
- Language: tv4 is written in JavaScript, while jsonschema is in Python
- Ecosystem: tv4 is more suited for JavaScript/Node.js projects, jsonschema for Python applications
- Features: jsonschema offers more extensive validation options and better support for recent JSON Schema drafts
- Community: jsonschema has a larger and more active community, with more frequent updates and contributions
Use Cases
- Choose tv4 for lightweight JSON Schema validation in JavaScript projects, especially when browser compatibility is required
- Opt for jsonschema in Python projects or when more advanced validation features and up-to-date JSON Schema support are needed
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
========== jsonschema
|PyPI| |Pythons| |CI| |ReadTheDocs| |Precommit| |Zenodo|
.. |PyPI| image:: https://img.shields.io/pypi/v/jsonschema.svg :alt: PyPI version :target: https://pypi.org/project/jsonschema/
.. |Pythons| image:: https://img.shields.io/pypi/pyversions/jsonschema.svg :alt: Supported Python versions :target: https://pypi.org/project/jsonschema/
.. |CI| image:: https://github.com/python-jsonschema/jsonschema/workflows/CI/badge.svg :alt: Build status :target: https://github.com/python-jsonschema/jsonschema/actions?query=workflow%3ACI
.. |ReadTheDocs| image:: https://readthedocs.org/projects/python-jsonschema/badge/?version=stable&style=flat :alt: ReadTheDocs status :target: https://python-jsonschema.readthedocs.io/en/stable/
.. |Precommit| image:: https://results.pre-commit.ci/badge/github/python-jsonschema/jsonschema/main.svg :alt: pre-commit.ci status :target: https://results.pre-commit.ci/latest/github/python-jsonschema/jsonschema/main
.. |Zenodo| image:: https://zenodo.org/badge/3072629.svg :alt: Zenodo DOI :target: https://zenodo.org/badge/latestdoi/3072629
jsonschema
is an implementation of the JSON Schema <https://json-schema.org>
_ specification for Python.
.. code:: 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'
It can also be used from the command line by installing check-jsonschema <https://github.com/python-jsonschema/check-jsonschema>
_.
Features
-
Full support for
Draft 2020-12 <https://python-jsonschema.readthedocs.io/en/latest/api/jsonschema/validators/#jsonschema.validators.Draft202012Validator>
,Draft 2019-09 <https://python-jsonschema.readthedocs.io/en/latest/api/jsonschema/validators/#jsonschema.validators.Draft201909Validator>
,Draft 7 <https://python-jsonschema.readthedocs.io/en/latest/api/jsonschema/validators/#jsonschema.validators.Draft7Validator>
,Draft 6 <https://python-jsonschema.readthedocs.io/en/latest/api/jsonschema/validators/#jsonschema.validators.Draft6Validator>
,Draft 4 <https://python-jsonschema.readthedocs.io/en/latest/api/jsonschema/validators/#jsonschema.validators.Draft4Validator>
_ andDraft 3 <https://python-jsonschema.readthedocs.io/en/latest/api/jsonschema/validators/#jsonschema.validators.Draft3Validator>
_ -
Lazy validation <https://python-jsonschema.readthedocs.io/en/latest/api/jsonschema/protocols/#jsonschema.protocols.Validator.iter_errors>
_ that can iteratively report all validation errors. -
Programmatic querying <https://python-jsonschema.readthedocs.io/en/latest/errors/>
_ of which properties or items failed validation.
Installation
jsonschema
is available on PyPI <https://pypi.org/project/jsonschema/>
. You can install using pip <https://pip.pypa.io/en/stable/>
:
.. code:: bash
$ pip install jsonschema
Extras
Two extras are available when installing the package, both currently related to format
validation:
* ``format``
* ``format-nongpl``
They can be used when installing in order to include additional dependencies, e.g.:
.. code:: bash
$ pip install jsonschema'[format]'
Be aware that the mere presence of these dependencies â or even the specification of format
checks in a schema â do not activate format checks (as per the specification).
Please read the format validation documentation <https://python-jsonschema.readthedocs.io/en/latest/validate/#validating-formats>
_ for further details.
.. start cut from PyPI
Running the Test Suite
If you have nox
installed (perhaps via pipx install nox
or your package manager), running nox
in the directory of your source checkout will run jsonschema
's test suite on all of the versions of Python jsonschema
supports.
If you don't have all of the versions that jsonschema
is tested under, you'll likely want to run using nox
's --no-error-on-missing-interpreters
option.
Of course you're also free to just run the tests on a single version with your favorite test runner.
The tests live in the jsonschema.tests
package.
Benchmarks
jsonschema
's benchmarks make use of pyperf <https://pyperf.readthedocs.io>
_.
Running them can be done via::
$ nox -s perf
Community
The JSON Schema specification has a Slack <https://json-schema.slack.com>
, with an invite link on its home page <https://json-schema.org/>
.
Many folks knowledgeable on authoring schemas can be found there.
Otherwise, opening a GitHub discussion <https://github.com/python-jsonschema/jsonschema/discussions>
_ or asking questions on Stack Overflow are other means of getting help if you're stuck.
.. end cut from PyPI
About
I'm Julian Berman.
jsonschema
is on GitHub <https://github.com/python-jsonschema/jsonschema>
_.
Get in touch, via GitHub or otherwise, if you've got something to contribute, it'd be most welcome!
You can also generally find me on Libera (nick: Julian
) in various channels, including #python
.
If you feel overwhelmingly grateful, you can also sponsor me <https://github.com/sponsors/Julian/>
_.
And for companies who appreciate jsonschema
and its continued support and growth, jsonschema
is also now supportable via TideLift <https://tidelift.com/subscription/pkg/pypi-jsonschema?utm_source=pypi-jsonschema&utm_medium=referral&utm_campaign=readme>
_.
Top Related Projects
An implementation of the JSON Schema specification for Python
A PHP implementation of JSON Schema validation
Tiny Validator for JSON Schema v4
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot