Validating JSON Data

On my first steps as Software Developer, I used to develop my own implementations of JSON validation, which worked great, but some JSONs were complex to validate, increasing complexity on improving the custom validators, becaming difficult to keep up these implementations. After some research, I discovered json-schema, which is a specification with drafts written for IETF and has implementations for many programing languages.

Here, I brought some examples on how to validate JSON data against schemas, based on its implementation for Python, including a small Web Application written in Flask.

Hope you enjoy it!

But what is JSON schema?

Quoting the first jsonschema draft for IETF:

JSON Schema defines the media type application/schema+json for describing the structure of other JSON documents. JSON Schema is JSON-based and includes facilities for describing the structure of JSON documents in terms of allowable values, descriptions, and interpreting relations with other resources.

Simple Validation => validate() method

This method throws out an exception, if any violation was detected, between data and schema:

Simple Validation => is_valid() method

I'd rather use this method instead of the prior, since that it just determines if a JSON is valid:

Lazy Validation => iter_errors() method

Probably one of the most interesting validation mechanisms, where you can gradually iterate over possible errors, without causing exceptions, and no need for try/except blocks.

The JSON schema specification has a series of versions, and here, we are using the Version 7:

Required Fields

Simple as it is, some fields are required, and if some of them are missed, the validation will fail:

Web Application Scenario

Here, a taste of JSON validation schema with JSON data over POST HTTP request:

The requests can be performed via Postman of just with simple cURL requests:


Command Line Scenario

You might want to validate some JSON files by hand, having a schema defined in a file as well:


Final Words

These are just a few examples and there are other functionalities like annotations, minimum and max length of fields, arrays validations, etc., that weren't exposed here. Although the examples here are simple, they have applicable features for complex structures as well, thanks to the solidity of JSON Schema standard.

If you have any question or suggestion, please, leave a comment. Thanks!

Mastodon