×

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

N2 in Python

N2 is known as Nearest Neighbor Algorithm, because it contains 2 N's (N-Nearest, N-Neighbor). This is a library in the python build using C++ and Python. Before N2 was made,...

3 minutes read.

OSError in 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...

4 minutes read.

How to Make an App with Python

In this age of mobiles, rapid mobile application development has got a lot of traction. Moreover, app developers are high in demand because of the increase in digitization. Generally, Python is...

4 minutes read.

XXhash 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...

6 minutes read.

Python Network Programming

In network programming, python plays a very important role. Python provides full support for encoding and decoding data and network protocol in its standard library. Writing a network program in...

3 minutes read.

Python issubclass() Function

Python issubclass() Function The issubclass() function in Python returns a boolean value ‘True’ if the given object is a subclass of classinfo, else it returns False. Syntax issubclass(class, classinfo) Parameter class: It is a required parameter which represents a tuple...

1 minute read.

Anaconda in Python 3

What is Anaconda in Python 3? Anaconda is an open-source package combining Python and R programming languages used for data analytics and processing data. It consists of a huge number of...

4 minutes read.

Arguments and parameters in Python

Generally, there is a misunderstanding that parameters and arguments, both are the same. But, as a programmer, you need to understand the difference between these two. Parameters: While defining a function, we...

5 minutes read.

Python Static Method

Introduction to methods that are majorly used in Python: Class MethodsInstance MethodsStatic Methods Before going to the in-depth concept of Static Methods, let us briefly discuss Class Methods and Instance Methods. Class Methods The...

4 minutes read.

How To Compare Two Strings In Python

In this article, we will discuss how to compare two strings in Python. So, before that, let’s have a quick revision on “What are strings?” Strings are a sequence of characters that...

5 minutes read.

Python Function

Python Function A Python function is a reusable, organized block of code that is used to perform the specific task. The functions are the appropriate way to divide an extensive program into a...

7 minutes read.

Python Dictionary setdefault() method

Python Dictionary setdefault() method The dictionary.setdefault () method in Python returns the value of the item with the specified key. Syntax dictionary.setdefault(keyname, value) Parameter keyname- This parameter represents the keyname of the item you want...

1 minute read.

Number Pattern Programs in Python

Learning Python is very easy, and it understands in better way compared to other programming languages. One of the many reasons why it has emerged as the most widely used...

4 minutes read.

Python Not Equal Operator

Python provides us with many operators to make tasks easier. There are about 7 categories of operators in Python. One of the 7 classifications is the comparison operators. Just as...

3 minutes read.

Allocate a minimum number of pages in python

You have given a sorted array of size n which represents the number of pages in n different books and an integer value which denotes the number of students. We...

4 minutes read.

Python pynmea2

Define Pynmea2 Python Programming Language: 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...

4 minutes read.

How to get current date in python?

How to get current date in python? In Python programming language, date and time are not just a data form, but it is possible to import a method called datetime to operate...

3 minutes read.

Matrix List Comprehension in Python

Introduction One of Python's most beautiful features is list comprehension. Iterating over an iterable object to create lists is a clever and succinct method. Nested List or matrix list Comprehensions, which...

6 minutes read.

Python SciPy Library

Introduction SciPy, a logical library for Python is an open-source, BSD-authorized library for arithmetic, science, and design. The SciPy library relies upon NumPy, which gives advantageous and quick N-dimensional exhibit control....

6 minutes read.

Reading a File Line by Line in Python

Introduction In this tutorial, we will learn about reading files in python line by line. Before reading the files, let us know a little information about the files first. Files A file is...

6 minutes read.