validate json using python

Lets go through the below script and see how can we validate JSON using Python. JSON or Javascript Object notion is an open standard format with attribute value and pair and is a famous alternative of xml

Validating json using python Script

In the below script we will see how can we validate the json to check if the format is correct using a small python script and mail will be sent in case there is some error with the json

#!/usr/bin/python
import json
import os
json_data=open(‘test.json’).read()
try:
data = json.loads(json_data)
except:
os.system(“echo \”json invalid\”|mailx -s \”json validation error\” -r MYMAILID@gmail.com”)

Lets analyze it in chunks : –

–  In the first line we are mentioning the path of python binary which will interpret the script

#!/usr/bin/python

– In second line we are importing module for json so that we can call load json using load function and in third line we are importing OS module to call system function to execute shell command for mail

import json
import os

– for fourth line we are opening the json file for reading and storing it in json_data variable, here we can also mention the full path along with filename .

json_data=open(‘test.json’).read()

– For rest of the remaining lines we are using the try and except block. Try block only executes when their is no error . While loading the json if their is any error except block will be initialized and mail will be sent to the respective mail id

try:
 data = json.loads(json_data)
except:
 os.system(“echo \”json invalid\”|mailx -s \”json validation error\” -r MYMAILID@gmail.com”)