×

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

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.

Is Python Case Sensitive

Case sensitivity is the mode of dealing with the written alphabet. The cases of the alphabet are examined and based on these words are being treated. The uppercase and lowercase...

3 minutes read.

Python lock

Before understanding the concept of Python-lock we need to understand what kind if condition we require to implement the locks in Python. Let us start with multithreading and its implementation...

5 minutes read.

Difference between For Loop and While Loop in Python

What is the “For” loop? The “For” Loop is a commonly used control structure in programming that allows us to repeat a set of actions multiple times. The “For” loop is...

3 minutes read.

Python Namespace

In python, the namespace is a very important concept that should be understood before using any function or variables. When we write code, we often use variables, libraries, functions, modules, etc....

4 minutes read.

Python Permutations and Combinations

In mathematics, we all studied what is meant by permutations and combinations. “Permutations” define the way of arranging the elements in sequential order. “Combinations” mean the way of selecting the...

7 minutes read.

Image to NumPy Arrays in Python

Image is a simple process of working model confined to machine learning, Python works with the image in the data format of width and height i.e. Images are excelled into...

3 minutes read.

Python Errors and exceptions

Exceptions and errors are the obstacles a programmer constantly faces while writing a program. Firstly, we need to understand what are errors and exceptions and the difference between these two...

6 minutes read.

How to Update Python?

How to Update Python In this article, we will discuss how we can update Python in our system. For a better understanding, this article will cover all the steps right from installation...

4 minutes read.

Python String replace() method

Python String replace() method The string.replace() method in Python returns a copy of the string with all occurrences of substring old replaced by new. Syntax replace(old, new[, count]) Parameter old: This parameter represents a substring you want to...

2 minutes read.

Math Module in Python

In this article, you are going to learn everything in detail about the “ math “ module in Python. We can normally work with general operations using python without importing or...

16 minutes read.

Copying a file from one folder to Another with Python

In this article, we shall discuss copying a file from one folder to another using python functions. A file is a collection of data or information stored on a computer....

3 minutes read.

Python K-Means Clustering

K-Means Clustering is a basic yet incredible calculation in information scienceThere are a plenty of true utilizations of K-Means clustering (a couple of which we will cover here)This far reaching...

25 minutes read.

Is Python Case-sensitive when Dealing with Identifiers

Yes, Python is a case-sensitive language while dealing with identifiers. Python is one of the top trending, widely-used programming languages. Python is a general-purpose programming language. It is a case-sensitive...

6 minutes read.

Iterators in Python

Introduction In Python, an iterator is defined as an object that enables traversing through all the values of a collection. It contains the countable number of values. The iterator is utilized to...

4 minutes read.

How to Import Files in Python

Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

How to Download all Modules in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

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.

List Comprehension in Python3

List A list in python is a complex data type, and a list is a collection of the number of data. The data variable may or may not be of the...

5 minutes read.

Python Assert

Python Assert Python provides an assert statement which is used to check the logical expression. If the given logical expression is true, then it precedes for the next line; otherwise, it raises an...

2 minutes read.