How to validate JSON schema in Python

In this post, we are going to learn How to validate JSON schema in Python. The JSON schema library helps in the implementation of JSON schema validation in python to validate JSON data or files. The JSON Schema is a specification for JSON-based format that defines the structure of JSON data. The JSON schema library provides a format to make a validator based on a given schema.

The benefits of using the JSON Schema


  • Describe existing data format(s).
  • Use to Validate data that are used in automatic testing.
  • It Provides clear human and machine readable documentation
  • Ensuring quality of client submitted data.
keywordDescriptions
$schemaIt states that this schema is written according to specific draft and standards and is primarily used for version control
$typeThe type validation keyword defines the first constraint on our JSON data and in this case, it has to be a JSON Object.
$idKeyword defines a URI for the schema and the base URI that other URI references within the schema are resolved against.
$propertiesDefine keys and the type of their values. The minimum and maximum values can be used in the JSON file.
$requiredThe list that keeps all required properties in the schema.
$title This keyword is used to mention the title of schema.
$descriptionThis keyword is used to give a little description of the schema.

1. Validate JSON schema in Python using jsonschema library


To validate a JSON response along with datatype the JSON schema library is used. By following the below steps we can easily validate JSON data against our custom define schema.

To make own schema validator. First, need to install the JSON schema library. We can make a schema of our own choice and validate the given file against the schema.

  • First, need to install jsonschema library using the pip command “pip install jsonschema “.
  • Secondly,import jsonschema using import jsonschema
  • Define the schema of our own choice that needs to validate against the JSON data.
  • Now convert JSON to python object using JSON.load() or JSON.loads() method.
  • Finally we will pass return result from load() or loads() to validate() method of jsonschema library

jsonschema validate example

import json
import jsonschema
from jsonschema import validate

# Describe JSON schema against we have validate JSON data
Emp_Schema = {
    "type": "object",
    "properties": {
        "Empname": {"type": "string"},
        "age": {"type": "number"},
        "Salary": {"type": "number"},
        "Dept": {"type": "string"},
    },
}

def validateJson_bySchema(jsonStr):
    try:
        validate(instance=jsonData, schema=Emp_Schema)
    except jsonschema.exceptions.ValidationError as error:
        return False
    return True


#convert JSON to python object

jsonStr = json.loads('{"Empname":"John", "age":30, "Salary":10000,"Dept":"IT"}')

#calling above define function
isJsonValid = validateJson_bySchema(jsonStr)
if isJsonValid:
    print('Given JSON data:\n ',jsonData)
    print("The JSON data is valid")
else:
    print(jsonData)
    print("The  JSON data is InValid")

Output

Given JSON data :
{'Empname': 'John', 'age': 30, 'Salary': 10000, 'Dept': 'IT'}
The JSON data is valid

2. Validate JSON schema Using Jsonchecker


json_checker is a library for validating Python data structures, such as those obtained from JSON (or something else) to Python data-types. json_checker has a parameter (soft=True) that allows you validate all JSON and raise all errors after validation was done”.

  • First we have to install json_checker by using pip command “pip install json-checker”
  • Sceondly we can import in our code using from json_checker import Checker
  • Finally using validate() to validate JSON data against schema.

Python JSON schema examples

from json_checker import Checker


# Describe JSON schema against which we have to validate JSON data
Emp_Schema = {  
        'Empname':str,
        "age": int,
        "Salary": int,
        "Dept": str
    
}




jsonStr ={"Empname":"John", "age":30, "Salary":10000,"Dept":"IT"}


checker = Checker(Emp_Schema)
result = checker.validate(jsonStr)
print(result)

Output

{'Empname': 'John', 'age': 30, 'Salary': 10000, 'Dept': 'IT'}

Summary

In this post, we have learned how to validate JSON schema in Python with examples by using two different libraries JSON Schema and Jsonchecker