validate json read in from file with a schema in python

To validate JSON read from a file with a JSON schema in Python, you can use the jsonschema library. Here's an example of how you can do it:

main.py
import json
import jsonschema

# Read the JSON schema from a file
with open('schema.json', 'r') as schema_file:
    schema = json.load(schema_file)

# Read the JSON data from a file
with open('data.json', 'r') as data_file:
    data = json.load(data_file)

# Validate the JSON data against the schema
try:
    jsonschema.validate(data, schema)
    print('JSON data is valid according to the schema.')
except jsonschema.exceptions.ValidationError as e:
    print('JSON data is not valid according to the schema.')
    print(e)
526 chars
19 lines

Make sure to replace 'schema.json' with the path to your JSON schema file and 'data.json' with the path to your JSON data file. If there are any validation errors, they will be raised as ValidationError exceptions with detailed error messages.

Note that you need to install the jsonschema library first by running pip install jsonschema.

related categories

gistlibby LogSnag