How to validate a JSON file using Python

To validate JSON data in Python, use the JSON module and exception handling to catch validation errors.

Method #1 Try to Load the JSON

Use the json.loads() function to attempt to parse the JSON data. This function raises a json.JSONDecodeError exception if the data is not valid JSON. Wrap the parsing in a try-except block to catch this exception:

Handle Validation Result

If the JSON is valid, parsed_data will contain the parsed dictionary or list. The code will print an error message and detail what went wrong if it’s invalid. Remember that this method only checks if the JSON is correctly formatted according to the JSON syntax rules. It does not validate the content or structure beyond the basic syntax.

JSON Validation Script:

import json

try:
    with open('data.json', 'r') as json_file:
        parsed_data = json.load(json_file)
        print("JSON is valid.")
except json.JSONDecodeError as e:
    print("JSON is not valid:", e)
except FileNotFoundError:
    print("File not found.")

If you’re validating a JSON file from a file path, you can use the same approach with json.load() instead of json.loads():

Replace ‘data.json‘ with your JSON file’s actual path and filename.

Remember that if you want to validate the JSON content against a specific schema or structure, you might need to use additional libraries or tools designed for JSON schema validation.

Method #2 Use a function

import json

def is_valid_json(json_string):
    try:
        # Try to load the JSON string
        json_object = json.loads(json_string)
    except json.JSONDecodeError as e:
        # The JSON string is not valid
        print(f"Invalid JSON: {e}")
        return False
    else:
        # The JSON string is valid
        return True

# Example usage

json_data = '{"name": "CodeTryout", "age": 30, "city": "New York"}'

if is_valid_json(json_data):
    print("JSON is valid.")
else:
    print("JSON is not valid.")

Replace the json_data variable with your actual JSON string or read the JSON data from a file using json.load if your JSON data is stored in a file. This approach checks the syntax of the JSON but does not check the content against a specific schema. If you need to validate JSON against a schema, you may want to explore additional libraries like jsonschema.

Choose the approach that best fits your needs, considering factors such as simplicity, error handling, and whether schema validation is required.

What is JSON File

A JSON file is a file that contains data in the JSON (JavaScript Object Notation) format. JSON is a lightweight data-interchange format that is easy for humans to read and write and for machines to parse and generate. It is commonly used to transmit data between a server and a web application and store configuration data, API responses, and more.

Example JSON file:

{
  "key1": "value1",
  "key2": 42,
  "key3": true,
  "key4": ["item1", "item2"],
  "key5": {
    "nestedKey": "nestedValue"
  }
}

In this example, the JSON object contains five key-value pairs. The values can be different, including strings, numbers, booleans, arrays, and objects.

The JSON Module

Python’s standard library provides the JSON module that helps encoding and decoding JSON (JavaScript Object Notation) data. The module offers two methods – json.dumps() for converting Python objects into a JSON-formatted string and json.loads() for parsing a JSON-formatted string into Python objects. This module is widely used for various tasks, including data interchange between systems, configuration file handling, and web development, where a lightweight and human-readable data format is necessary.