Validate JSON data using Python

In this post, I’ll explain to you how you can validate JSON data using Python so let’s get started.

JSON

JSON is (JavaScript Object Notation)  used to store the data it is a lightweight data-interchange format. It is based on JavaScript Programming Language, it is easy to read and write data in this file format. JSON has format like JavaScript objects.

For more information about JSON file format refer to the following link https://www.json.org

A JSON contains key and value pairs like Python dictionaries, key is the unique string that can’t be null while value is a string, number, boolean, list, or even null.

Why JSON is required

JSON is commonly used in transmitting data in web applications from server to client and from client to server so that it can be displayed on web pages. 

Validating JSON data using Python

Before doing that let me first explain to you about JSON Schema is a vocabulary that is used to validate the JSON file and also allow you to annotate it.’

We will use jsonschema library for the implementation of JSON Schema in Python.

You can install it using  pip install jsonschema command. 

And with the help of this jsonschema library we’ll validate the JSON data in python.

We’ll use validate() function for validating our JSON data. 

Note.1:-To validate JSON data using Python firstly you must have to import jsonschema.

Note.2:- I recommend you to please read every comment in my code to understand the working of code clearly.

#Program for validating JSON data in Python
#we import json, jsonschema and jsonschema validate() for validating 
#our JSON data using python
import json
import jsonschema
from jsonschema import validate

# JSON data that we want to validate.
MySchema = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "roll": {"type": "number"},
        "marks": {"type": "number"},
    },
}

#function for cheking validation of JSOn data
def validateJson(jsonData):
#we define try except for handling exception if our data is inavlid
    try:
        validate(instance=jsonData, schema=MySchema)
    except jsonschema.exceptions.ValidationError as err: 
        #if our data is invalid then it will throw an error and return false 
        return False 
    return True

# Convert json to python object. json.loads() will load our data in JSON format for validation
jsonData1 = json.loads('{"name": "jane doe", "rollnumber": "25", "marks": "72"}') 
#our jsonData1 is Invalid bceause we pass the string value to our roll and marks key 
#in place of number value so it will so inavlid json data
# validate it
isValid = validateJson(jsonData1)
if isValid:
    print(jsonData1)
    print("Given JSON data is Valid")
else:
    print(jsonData1)
    print("Given JSON data is InValid")

# Convert json to python object.
jsonData2 = json.loads('{"name": "jane doe", "rollnumber": 25, "marks": 72}')
# validate it
#jsonData2 is valid json data because it contains the correct value types
isValid = validateJson(jsonData2)
if isValid:
    print(jsonData2)
    print("Given JSON data is Valid")
else:
    print(jsonData2)
    print("Given JSON data is InValid")

Output

{'name': 'jane doe', 'rollnumber': '25', 'marks': '72'}
Given JSON data is InValid
{'name': 'jane doe', 'rollnumber': 25, 'marks': 72}
Given JSON data is Valid

 

Leave a Reply

Your email address will not be published.