×

Python JSON Schema

Python-jsonschema

JSON: JSON stands for JavaScript Object Notation. It is a text-based format that represents structured data and can be used to interchange data among various applications. This is self-defining language and is easy to understand.

jsonschema: It is used to validate the JSON documents. The validated data that we get can be used for automated testing and ensuring that quality data is sent and received by the clients. It is human and machine-readable documentation. It is a contract that states that defines the data types and the format of the datatypes.

Jsonschema is the implementation of the specification of JSON schema in python.

KeywordDefinition and its function
$schemaThis specifies that the schema and its properties are defined as stated in the draft v4 specification. It ensures the compiler that the program is written follows all the stated The $schema keyword states that this schema is written according to the draft v4 specification. It can be used to declare the version of the JSON schema.
titleIt is used to add the title to your schema so that it can be identified for future use.
descriptionIt describes the various elements of the schema and its features.
typeIt states that Jsonschema can only be applied to JSON files and cannot be implemented on any other file.
propertiesIt defines the various elements of the data structure, it contains all the key values and the minimum and maximum values that can be held by those keys.
requiredThis keeps the track of all the properties that are must for the implementation of the schema.
minimumThis is the constraint that is defined on the key, it specifies the minimum value held by the key any value below it is not expected.
Exclusive minimumIt is exceptional and the user needs to decide to use it in schema or not, it takes Boolean values as input. If it is assigned True as the value, the value of the instance must be greater than the value passed to the minimum.
maximumThis is the constraint that is defined on the key, it specifies the maximum value held by the key any value above it is not expected.
exclusiveMaximumIt is also exceptional as the user decides to implement it in the schema or not, it takes Boolean values as input. If it is assigned True as the value, the value of the instance must be smaller than the value passed to the minimum.
multipleOfIt determines whether the numeric value is the multiple of this keyword value or not, that is the result of this dividing the numeric instance by the keyword’s value should be an integral value.
maxLengthIt represents the maximum number of characters that can be stored in a string instance. It can be defined as the maximum length of the string.
minLengthIt represents the minimum number of characters that can be stored in a string instance.
patternIt matches the string instance and determines whether the string instance matches the sequence of characters of the regular expression. It is only valid if the string instance is a match for the regular instance.

Json Schema Validation

Using the JSON schema makes the process of validating the API easier as you can construct the model of your API response. It enables the user to monitor the response of the API and ensure that the response we get is the same as the expected response.

It gives an alert when there is a breaking change in the response as the schema will not approve the data in the wrong format.

Implementing jsonschema in Python

To implement jsonschema you need to follow these basic steps each time:

  1. Install jsonschema in your system using pip
  2. Describe the schema of the JSON document
  3. Convert the received JSON file into an object of python using json.load() method
  4. This python object is then passed through the validate function, which will match the structure of the file from the structure defined in the schema. If the structure does not match, then it will throw an exception.

Installing the Jsonschema

It can be installed in the system like any other library of python using the pip installer. Type the “pip install jsonschema” command in the command prompt or the terminal of your system.

Validating the Data

Let us consider an example, we will validate a patient record from a hospital. Here the patient record is required to specify the name of the patient, patient id and the number of visits by the patient.

The JSON document must meet the following conditions to be a valid JSON:

  1. The patient name and patientid must be present in the JSON Data.
  2. Patient name should be in string format while the patientid and visits must be number.
import json
import jsonschema
from jsonschema import validate

# Describe the structure of the JSON document that you want to validate
patientSchema = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "patientid": {"type": "number"},
        "doc_name": {"type": "string"},
        "visits": {"type": "number"},
    },
}

def validateJson(patientData):
    try:
        validate(instance=patientData, schema=patientSchema)
    except jsonschema.exceptions.ValidationError as err:
        return False
    return True

# this method takes the json data and changes it to a python object.
patientData = json.loads('{"name": "Patient1", "patientid": "100","doc_name":"Doctor1", "visits": 3}')
# Now check whether the entered data is valid according to the schema
isValid = validateJson(patientData)
if isValid:
    print(patientData)
    print("The entered data is valid")
else:
    print(patientData)
    print("This data is invalid please enter the data again")

# Second JSON data converted to a Python object.
patientData = json.loads('{"name": "Patient2", "patientid": 101,"doc_name":"Doctor1", "visits": 5}')
# Performing validation on the second JSON data
isValid = validateJson(patientData)
if isValid:
    print(patientData)
    print("The entered data is valid")
else:
    print(patientData)
    print("This data is invalid please enter the data again")

CONCLUSION

The first JSON data is invalid as the patientid is a string, while in the schema we have defined its format as a number.
In the case of second data, all the corresponding data is in the same format as specified in the JSON schema.


Related Topics

Working with JSON in Python

Python is an Object-Oriented high-level language. Python is designed to be highly beginner-friendly. Python has an English-like syntax, which is very easy to read. In this article, we are going...

4 minutes read.

Binary Search Visualization using Pygame in Python

A calculation like Binary Search is seen effectively by picturing. Here in this tutorial, a function that pictures the Binary Search Algorithm is carried out. The Graphical User’s Interface (GUI)...

15 minutes read.

Spyder (32-bit) - Free download

Spyder is a free and open-source scientific environment created by and for Python engineers, scientists, and data analysts. It is a robust scientific environment created in Python by and for...

3 minutes read.

Check whether dir is empty or not in python

Python: Check if a directory is empty In this tutorial, we will study how to check whether the director (dir) is empty or not in the python programming language. First of...

3 minutes read.

Uint8 Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Python Parallel Processing

By performing more jobs concurrently, your software may complete more tasks in a shorter amount of time. These aid in solving major issues. The following subjects will be covered in...

2 minutes read.

How to Write a Configuration file in Python

This article will discuss How to write a configuration file in python, why we need config files in Python, the format of the configuration file, file extensions, and how to...

11 minutes read.

Python Program to Convert Decimal into Binary, Octal, and Hexadecimal

Python Program to Convert Decimal into Binary, Octal, and Hexadecimal We know that the most widely used number system is a decimal system, but the computer only understands binary values. The...

2 minutes read.

Cube Root in Python

In general, the cube is a three-dimensional solid figure that has 6 square faces. It is also called a geometrical shape with six equal faces, eight vertices, and twelve edges....

3 minutes read.

*Args and **Kwargs in Python

Let’s know about ** (dual star / asterisk) and * (star / asterisk) are operators in Python. These stars are used in Python for parameters. Args and kwargs are special...

3 minutes read.

Parameter Passing in Python

In Python, when we characterize capabilities with default values for specific boundaries, it is said to have its contentions set as a possibility for the client. Clients can either pass their...

3 minutes read.

Difference between Expression and Statement in Python

What is an expression in Python? Expression is a combination of operands and operators. Expression helps us to produce some other values. In the python programming language,  expressions produce some other value...

6 minutes read.

Python Web Development projects

What is Python? Python is currently one of the most widely used computer programming languages. This isn't just an exaggeration; Python is the second-most famous programming language on the software development...

3 minutes read.

Python sorted() function

Python sorted() function The sorted() function returns a sorted list of the specified iterable object. Syntax sorted(iterable, *, key=None, reverse=False) Parameter iterable: It is a required parameter that represents the sequence to sort, list, dictionary, tuple etc. key:...

1 minute read.

How to Install Tweepy in Python

In this article, we will learn or understand how to install Tweepy in Python and what Tweepy is. Firstly, let’s understand What Tweepy is. As we all know, one of the...

3 minutes read.

Python filter() function

Python filter() function The filter() function constructs an iterator from those elements of iterable for which the parameter ‘function’ returns a Boolean value true. Syntax filter(function, iterable) Parameter function: This parameter represents a function to be run for each item in the...

1 minute read.

Python setattr() function

Python setattr() function The setattr() function sets the value of the specified attribute of the specified object. Syntax setattr(object, name, value) Parameter object: This parameter represents any object. name: This parameter represents the name of the attribute you...

1 minute read.

Multiprocessing in python

The word multiprocessing is used to compute the operation in which more than two processors run simultaneously with more than one central processor. The computer's performance increases gradually. Multiprocessing is...

6 minutes read.

Python max() function

Python max() function The max() function in Python returns the largest item in an iterable or the largest of two or more arguments. Syntax max(iterable, *[, key, default])               or max(arg1, arg2, *args[, key])   Parameter arg1, arg2, *args: This...

1 minute read.

Python md5() function

Python md5() function The md5() function in PHP calculates the md5 hash of a string. Syntax md5 ( string $str [, bool $raw_output] ) Parameter str(required)- This parameter specifies the string. raw_output(optional)- This parameter specifies a hex or binary output format: TRUE - Raw 16 character binary...

1 minute read.