How to validate JSON in Python : Step by Step

How to validate JSON in Python

Do you have a Json data as a string or response from the api request and wants to validate it? If yes then this post is for you. In this tutorial you will know how to validate JSON data in python through steps.

Problem Statement

You have a JSON data fetched by any means and you want to check the validity of the JSON response.

Steps to Validate JSON in Python

Let’s learn all the steps to validate JSON data in python. Follow the steps for deep understanding.

Step 1: Impor the JSON module

The first step is to import the JSON module. The json module is already inside Python. Import it using the import statement.

import json

Step 2: Create a simple JSON string

The next step is to create a sample json string. It is only for demonstration purposes. You can use your own JSON string.

json_string = '{"website": "Data Science Learner", "topics": ["Data Science", "Python", "Numpy"]}'

Step 3: Use the json.loads() function

After the creation of the json string use the json.loads() function for JSON validation. Just pass the sample json to json.loads() function as argument.

Use the lines below of code to achieve that.

try:
    json_data = json.loads(json_string)
    print("Basic JSON validation successful.")
    print(json_data)
except json.JSONDecodeError as e:
    print(f"Error decoding JSON: {e}")

Here I have used the try and except to manage the exception. If the Json is valid then it will print the successful message and if it is not then output the decoding error.

Full code

import json
json_string = '{"website": "Data Science Learner", "topics": ["Data Science", "Python", "Numpy"]}'
try:
    json_data = json.loads(json_string)
    print("Basic JSON validation successful.")
    print(json_data)
except json.JSONDecodeError as e:
    print(f"Error decoding JSON: {e}")

Output

Basic JSON validation
Basic JSON validation

Steps to Validate JSON Schema

The above steps were for the simple JSON string. Let’s say you have json schema and want to validate it then you will use the below steps.

Step 1: Install the JSON schema module

The first step is to the jsonschema module. If it is installed in your system then move to step 2.

For python 2.xx

pip install jsonschema

For python 3.xx

pip3 install jsonschema

Step 2:  Create a sample JSON Schema

The next step is to create a sample JSON schema that will be used for demonstration purposes.

schema = {
    "type": "object",
    "properties": {
        "website": {"type": "string"}, "topics": {"type": "array"} }, "required": ["key", "array"] } 

 

Step 3: Use the json.loads() function

In this step you will convert the JSON string as JSON object using the json.loads() function.

json_data = json.loads(json_string)

Step 4: Use the validate constructor

Now you have to use the validate constructor and pass the instance = josn_data and schema as arguments.

from jsonschema import validate
validate(instance=json_data, schema=schema)

You will use the below lines of code.

try:
    json_data = json.loads(json_string)
    validate(instance=json_data, schema=schema)
    print("JSON validation against schema successful.")
    print(json_data)
except json.JSONDecodeError as e:
    print(f"Error decoding JSON: {e}")
except Exception as e:
    print(f"Validation error: {e}")

Full code


import json
from jsonschema import validate
json_string = '{"website": "Data Science Learner", "topics": ["Data Science", "Python", "Numpy"]}'

schema = {
    "type": "object",
    "properties": {
        "website": {"type": "string"}, "topics": {"type": "array"} }, "required": ["key", "array"] } 

json_data = json.loads(json_string)
validate(instance=json_data, schema=schema)
try:
    json_data = json.loads(json_string)
    validate(instance=json_data, schema=schema)
    print("JSON validation against schema successful.")
    print(json_data)
except json.JSONDecodeError as e:
    print(f"Error decoding JSON: {e}")
except Exception as e:
    print(f"Validation error: {e}")

Output

ValidationError: 'key' is a required property

Failed validating 'required' in schema:
    {'properties': {'topics': {'type': 'array'},
                    'website': {'type': 'string'}},
     'required': ['key', 'array'],
     'type': 'object'}

On instance:
    {'topics': ['Data Science', 'Python', 'Numpy'],
     'website': 'Data Science Learner'}

Conclusion

Many web developers used JSON response for building apps. Thus it becomes necessat that the JSON response should be validate. The above steps will validate JSON string as well as JSON schema easily.

I hope you have liked this tutorial. If you have any queries then you can contact  us for more help.

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Meet Sukesh ( Chief Editor ), a passionate and skilled Python programmer with a deep fascination for data science, NumPy, and Pandas. His journey in the world of coding began as a curious explorer and has evolved into a seasoned data enthusiast.
 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner