How to validate JSON data in Python

In this post, we are going to learn how to validate JSON data in Python. We first check if a given string is valid JSON as per standard convention format. In Python that can be achieved by using JSON module built-in methods loads() which checks if a string is valid JSON or load() to validate the contents of the file are valid JSON. The JSON. Tool module is also used to validate a file by the command line. We will understand each of them will python code examples.

Methods to check string or file is valid JSON


  • json.loads() : check if a string is valid json
  • json.load() : This method to validate a string from a file.

Note : The json.loads() or json.load() method throw valuerror,if given string is not valid json

1. Python Check if a string is valid json


To check if the string is valid JSON in Python, We will use the JSON module that is imported using “import JSON“, First need to make sure the JSON module is installed or we can install it using “pip install jsonlib-python3”.

  • Inside the try/exception block, we have used JSON.loads() method to parses the given string.
  • if the string is valid JSON then it parses the JSON.s
  • When a string is not valid JSON then it raises ValueError, and the exception block will execute.
import json
json_string = '{ "Empname":"John", "age":30, "Salary":10000,"Dept":"IT"}'

try:
	json = json.loads(json_string)
	print('valid json string')
except ValueError as error:
	print("invalid json string:\n",error)

Output

valid json string:

2. Python validate json file


Sometimes instead of checking if a string is valid JSON we have to validate file content is valid JSON that simply can be done by using the JSON module load() method. In this example First, we are opening a file using the open() method and checking if it contains valid JSON data using the load() method.

  • if the file contents are valid JSON then this function parse the given file and return True.
  • when the file contents are not valid json then load() method raise ValueError and exception block will execute and return False
import json

def check_valid_JSOn(filename):
    try:
        with open(filename) as file:
         parse_json = json.load(file)
         print(parse_json) 
         return True
    except ValueError as e:        
        return False

print('Valid JSOn File :',check_valid_JSOn('data.json'))

Output

{'Empname': 'John', 'age': 30, 'Salary': 10000, 'Dept': 'IT'}
Valid JSOn File : True

3. Python validate json file command line


To validate a file content is valid JSON instead of directly parsing it. we can check it before parsing by using the command line with the help of the following JSON.tool module command “python -m json.tool filename”.

C:\Users\Admin\Desktop\Python_program>python -m json.tool data.json 

Output

{
    "Empname": "John",
    "age": 30,
    "Salary": 10000,
    "Dept": "IT"
}

Summary

In this post, we have learned How to validate JSON data in Python by using JSON and JSOm.tool modules. We have checked if a string is valid JSON, Python validates JSON file, Python validates JSON file command line.