How To Validate JSON Schema In Python | Lillian Purge

Learn how to validate JSON Schema in Python using the jsonschema library, handle errors, and enforce formats with best practice.

How To Validate JSON Schema In Python

Validating JSON Schema in Python is a practical skill, especially when you are receiving data from APIs, forms, webhooks, or third party systems and you need to confirm it matches a required structure before you trust it. From experience most bugs in data pipelines come from assumptions, and schema validation is how you replace assumptions with certainty.

In my opinion the cleanest approach in Python is to use the jsonschema library. It is widely used, straightforward, and supports modern JSON Schema standards. Validation typically involves defining a schema as a Python dictionary, loading your JSON data into a dict, then running a validator that raises an exception if the data does not conform.

Below is a clear, practical way to do it, along with a few gotchas I see people miss.

Installing The jsonschema Library

To validate JSON Schema you first need a library that understands the JSON Schema standard. In Python the most common choice is jsonschema.

You can install it using pip. Once installed you can import it and validate data structures that are already loaded as Python dictionaries.

pip install jsonschema

From experience it is worth pinning the version in production systems, because JSON Schema standards and library behaviour can change over time.

A Simple Example Schema And JSON Payload

A JSON Schema is itself JSON, which means in Python it is usually represented as a dictionary. The data you want to validate is also represented as a dictionary after parsing.

Here is a simple example. Imagine you expect a user object with a name, an age, and an email address. You can define that schema with required fields and type rules.

Python

from jsonschema import validate, ValidationError schema = { "type": "object", "properties": { "name": {"type": "string", "minLength": 1}, "age": {"type": "integer", "minimum": 0}, "email": {"type": "string", "format": "email"}, }, "required": ["name", "age", "email"], "additionalProperties": False, } payload = { "name": "Sam", "age": 34, "email": "sam@example.com", } try: validate(instance=payload, schema=schema) print("Valid JSON ✅") except ValidationError as e: print("Invalid JSON ❌") print(e.message)

From experience this pattern covers most use cases. If the payload breaks the rules, the library throws a ValidationError, and you can return a clear message or log the details.

Validating JSON Loaded From A String Or File

Often your JSON data arrives as a string, for example from an API response or a webhook. In that case you parse it first using the built in json module, then validate it.

Python

import json from jsonschema import validate, ValidationError schema = {"type": "object"} # replace with your real schema json_text = '{"hello": "world"}' payload = json.loads(json_text) try: validate(instance=payload, schema=schema) print("Valid JSON ✅") except ValidationError as e: print("Invalid JSON ❌", e.message)

The key point is that jsonschema validates Python structures, not raw JSON strings, so parsing is always step one.

Making Format Checks Work Properly

A common gotcha is the "format" keyword, like "format": "email".

The validator will only enforce those format rules if you provide a FormatChecker. Without it, format fields may be accepted even when they are clearly invalid.

Here is what a strict format validation looks like:

Python

from jsonschema import Draft202012Validator, FormatChecker, exceptions schema = { "type": "object", "properties": {"email": {"type": "string", "format": "email"}}, "required": ["email"], } payload = {"email": "not-an-email"} validator = Draft202012Validator(schema, format_checker=FormatChecker()) errors = sorted(validator.iter_errors(payload), key=lambda e: e.path) if errors: for err in errors: print(f"Error at {list(err.path)}: {err.message}") else: print("Valid JSON ✅")

From experience this approach is better than validate() when you want multiple errors returned rather than failing on the first one.

Choosing A JSON Schema Draft Version

JSON Schema has draft versions, and different tooling behaves slightly differently depending on which draft you target.

If you are working with newer schema features, it is safer to use an explicit validator like Draft202012Validator or Draft7Validator rather than relying on defaults.

From experience Draft 7 is still very common, but if you are using schema built for newer drafts, using the matching validator avoids surprises.

Validating The Schema Itself

Another useful capability is validating that your schema is valid JSON Schema. This is especially important when schemas are user supplied or stored externally.

Most validators provide a method to check the schema.

Python

from jsonschema import Draft202012Validator schema = {"type": "object", "properties": {"a": {"type": "string"}}} Draft202012Validator.check_schema(schema) print("Schema is valid ✅")

From experience doing this once at startup or when loading schemas prevents runtime confusion later.

Handling Nested Objects And Arrays

Schema validation becomes most valuable when dealing with nested structures.

For arrays you define "type": "array" and specify "items" describing what each entry should look like. For nested objects you define properties recursively.

This allows you to enforce strict shapes, for example a list of orders where each order has an id and line items.

From experience being explicit about nested requirements prevents the most expensive classes of data bugs.

What To Return When Validation Fails

In real applications you usually want validation errors that are meaningful to humans.

The raw exception message is useful but not always user friendly. Iterating errors and formatting paths into something readable helps a lot.

From experience returning a list of errors with field paths such as order.items[0].sku makes debugging far easier than one generic failure message.

Performance Considerations

Validation is fast enough for most normal workloads but if you validate large volumes of payloads it is worth reusing a compiled validator rather than calling validate() repeatedly.

From experience creating a validator once and reusing it in a loop improves performance and keeps error handling consistent.

Final Thoughts On How To Validate JSON Schema In Python

In my opinion JSON Schema validation is one of the best ways to make Python systems more reliable, because it forces data to match expectations before you process it.

The most practical approach is to use the jsonschema library, define your schema clearly, parse JSON into a Python dictionary, then validate using an explicit draft validator so behaviour is predictable. If you add format checking and return readable error paths you end up with validation that is robust, maintainable, and easy to debug.

Maximise Your Reach With Our Local SEO

At Lillian Purge, we understand that standing out in your local area is key to driving business growth. Our Local SEO services are designed to enhance your visibility in local search results, ensuring that when potential customers are searching for services like yours, they find you first. Whether you’re a small business looking to increase footfall or an established brand wanting to dominate your local market, we provide tailored solutions that get results.

We will increase your local visibility, making sure your business stands out to nearby customers. With a comprehensive range of services designed to optimise your online presence, we ensure your business is found where it matters most—locally.

Strategic SEO Support for Your Business

Explore our comprehensive SEO packages tailored to you and your business.

Local SEO Services

From £550 per month

We specialise in boosting your search visibility locally. Whether you're a small local business or in the process of starting a new one, our team applies the latest SEO strategies tailored to your industry. With our proven techniques, we ensure your business appears where it matters most—right in front of your target audience.

SEO Services

From £1,950 per month

Our expert SEO services are designed to boost your website’s visibility and drive targeted traffic. We use proven strategies, tailored to your business, that deliver real, measurable results. Whether you’re a small business or a large ecommerce platform, we help you climb the search rankings and grow your business.

Technical SEO

From £195

Get your website ready to rank. Our Technical SEO services ensure your site meets the latest search engine requirements. From optimized loading speeds to mobile compatibility and SEO-friendly architecture, we prepare your website for success, leaving no stone unturned.

With Over 10+ Years Of Experience In The Industry

We Craft Websites That Inspire

At Lillian Purge, we don’t just build websites—we create engaging digital experiences that captivate your audience and drive results. Whether you need a sleek business website or a fully-functional ecommerce platform, our expert team blends creativity with cutting-edge technology to deliver sites that not only look stunning but perform seamlessly. We tailor every design to your brand and ensure it’s optimised for both desktop and mobile, helping you stand out online and convert visitors into loyal customers. Let us bring your vision to life with a website designed to impress and deliver results.