Yes, there are packages that can help you get more detailed and user-friendly error messages when validating JSON data against a schema. One such package is jsonschema-path, which provides more detailed error paths and can be more helpful in diagnosing validation issues, especially with complex schemas like those using anyOf.
Here’s how you can use jsonschema-path to get more detailed error messages:
Installation
First, you need to install the jsonschema-path package:
pip install jsonschema-path
Usage
Here’s an example of how to use jsonschema-path to get detailed validation errors:
import json
from jsonschema_path import SchemaPath, validate
# Define your schema with anyOf
schema = {
"type": "object",
"anyOf": [
{
"properties": {
"name": {"type": "string"},
"age": {"type": "integer", "minimum": 0}
},
"required": ["name", "age"]
},
{
"properties": {
"name": {"type": "string"},
"role": {"type": "string", "enum": ["admin", "user"]}
},
"required": ["name", "role"]
}
]
}
# Define your data
data = {
"name": 123, # This should be a string in both schemas
"age": -5 # This should be a non-negative integer in the first schema
}
try:
# Attempt to validate the data against the schema
validate(instance=data, schema=SchemaPath(schema))
except jsonschema.exceptions.ValidationError as e:
# Print detailed error information
print(json.dumps(e.json(), indent=2))
Explanation:
SchemaPath: This class from jsonschema-path enhances the schema with more detailed error reporting capabilities.
validate: The validate function from jsonschema-path is used to validate the data against the schema.
e.json(): When a validation error occurs, the exception object e has a json method that provides a detailed JSON representation of the error, including the schema path and instance path.
Output:
The output will be a detailed JSON representation of the validation errors, including the paths within the schema and instance where the validation failed.
[
{
"message": "123 is not of type 'string'",
"schema_path": [
"anyOf",
0,
"properties",
"name",
"type"
],
"instance_path": [
"name"
],
"instance_value": 123
},
{
"message": "-5 is less than the minimum of 0",
"schema_path": [
"anyOf",
0,
"properties",
"age",
"minimum"
],
"instance_path": [
"age"
],
"instance_value": -5
},
{
"message": "123 is not of type 'string'",
"schema_path": [
"anyOf",
1,
"properties",
"name",
"type"
],
"instance_path": [
"name"
],
"instance_value": 123
},
{
"message": "'age' is not one of ['admin', 'user']",
"schema_path": [
"anyOf",
1,
"required"
],
"instance_path": [],
"instance_value": {
"name": 123,
"age": -5
}
}
]