When using the python jsonschema package and a value fails to validate, the error message is fairly useless, just saying that it failed to validate against the entire schema. Is there a way to get a more focused error message, such as the closest match within the schema and a specific record that failed to match rather than just dumping the whole of the schema?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Yes, the default error messages from jsonschema can be quite verbose and unhelpful. There are several ways to get more focused, actionable error messages:
Use the ErrorTree for structured access
The ErrorTree class lets you navigate validation errors in a structured way:
python
import jsonschema
from jsonschema import ErrorTree
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer", "minimum": 0}
},
"required": ["name"]
}
data = {"name": 123, "age": -5}
try:
jsonschema.validate(data, schema)
except jsonschema.ValidationError as e:
errors = ErrorTree(e)
# Check specific field errors
if "name" in errors:
print(f"Name error: {errors['name'].message}")
if "age" in errors:
print(f"Age error: {errors['age'].message}")
Extract key information from ValidationError
You can pull out the most relevant parts of a ValidationError:
python
try:
jsonschema.validate(data, schema)
except jsonschema.ValidationError as e:
print(f"Field: {'.'.join(str(x) for x in e.absolute_path)}")
print(f"Value: {e.instance}")
print(f"Error: {e.message}")
print(f"Failed constraint: {e.validator} = {e.validator_value}")
Use iter_errors() for multiple validation issues
This gives you all validation errors at once, which is especially useful for forms:
python
validator = jsonschema.Draft7Validator(schema)
errors = list(validator.iter_errors(data))
for error in errors:
field_path = ".".join(str(x) for x in error.absolute_path) or "root"
print(f"{field_path}: {error.message}")
Create custom error formatting
You can write a helper function to format errors exactly how you want:
python
def format_validation_error(error):
field = ".".join(str(x) for x in error.absolute_path) or "root"
return f"Validation failed for '{field}': {error.message} (got: {error.instance})"
try:
jsonschema.validate(data, schema)
except jsonschema.ValidationError as e:
print(format_validation_error(e))
The absolute_path, instance, and message attributes of ValidationError are usually the most useful for creating focused error messages that tell you exactly what field failed and why, without dumping the entire schema.
User
This doesn't help; my schema has some anyOf values, and I get just that none of the options matches and e.validator_value just ends up being the whole of the schema.
Assistant
You're right - anyOf validation errors are particularly unhelpful because jsonschema just tells you "none of the schemas matched" without showing you how close each option came to matching. Here are some better approaches:
Manually validate against each anyOf option
python
import jsonschema
def get_detailed_anyof_errors(data, schema):
if 'anyOf' not in schema:
# Regular validation
try:
jsonschema.validate(data, schema)
return None
except jsonschema.ValidationError as e:
return [e]
# For anyOf, try each option and collect errors
errors_per_option = []
for i, sub_schema in enumerate(schema['anyOf']):
validator = jsonschema.Draft7Validator(sub_schema)
option_errors = list(validator.iter_errors(data))
errors_per_option.append({
'option_index': i,
'schema': sub_schema,
'errors': option_errors,
'error_count': len(option_errors)
})
# Sort by fewest errors (closest match)
errors_per_option.sort(key=lambda x: x['error_count'])
return errors_per_option
# Usage
schema = {
"anyOf": [
{"type": "string", "minLength": 5},
{"type": "integer", "minimum": 10},
{"type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"]}
]
}
data = {"name": 123} # Close to option 3 but name is wrong type
results = get_detailed_anyof_errors(data, schema)
if results:
best_match = results[0]
print(f"Closest match was option {best_match['option_index']} with {best_match['error_count']} errors:")
for error in best_match['errors']:
field = ".".join(str(x) for x in error.absolute_path) or "root"
print(f" {field}: {error.message}")
User
Are there any packages that have functions to do this in a more automated way? I'd hate to maintain code if someone has already done a good job of showing the closest match
Assistant
Yes, there are several packages that handle this better than raw jsonschema:
jsonschema-error-formatter
This package specifically focuses on making jsonschema errors more readable:
python
from jsonschema_error_formatter import format_error
import jsonschema
try:
jsonschema.validate(data, schema)
except jsonschema.ValidationError as e:
print(format_error(e))
It handles anyOf cases better by showing which options were tried and why they failed.
better-jsonschema-errors
Another package designed specifically for this problem:
python
from better_jsonschema_errors import ValidationError as BetterValidationError
import jsonschema
try:
jsonschema.validate(data, schema)
except jsonschema.ValidationError as e:
better_error = BetterValidationError(e)
print(better_error.message)
jsonschema-spec (with error analysis)
This is a more comprehensive package that includes better error reporting:
python
from jsonschema_spec import validate
try:
validate(data, schema)
except Exception as e:
print(e) # Much more detailed error messages
cerberus
If you're open to switching validation libraries entirely, Cerberus provides much better error messages out of the box:
python
from cerberus import Validator
# Convert your JSON schema to Cerberus format (some manual work required)
schema = {
'name': {'type': 'string', 'required': True},
'age': {'type': 'integer', 'min': 0}
}
v = Validator(schema)
if not v.validate(data):
print(v.errors) # Much cleaner error format
pydantic
For Python objects specifically, Pydantic gives excellent validation errors:
python
from pydantic import BaseModel, ValidationError
from typing import Union
class Person(BaseModel):
name: str
age: int
try:
person = Person(**data)
except ValidationError as e:
print(e) # Very clear, field-specific errors
My recommendation: If you're stuck with jsonschema, try jsonschema-error-formatter or better-jsonschema-errors first. If you have flexibility in your validation approach, Pydantic provides the best error messages for Python data validation, though it requires defining schemas as Python classes rather than JSON.
The jsonschema-error-formatter package specifically addresses the anyOf problem you're facing and should give you much more actionable error messages without having to maintain custom code.
User
Given the error from jsonschema, I see I can do """for error in errors:
for suberror in sorted(error.context, key=lambda e: e.schema_path):
print(list(suberror.schema_path), suberror.message, sep=", ")"""
Assistant
Excellent discovery! You're absolutely right - the context attribute on ValidationError is the key to getting detailed information about anyOf failures. This is much cleaner than manually validating against each option.
The context contains the individual validation errors from each anyOf option that was tried. Your approach of sorting by schema_path is smart because it gives you a consistent ordering to see which specific constraints failed.
You can enhance this further:
python
for error in errors:
if error.validator == 'anyOf':
print(f"anyOf validation failed. Here's what each option required:")
for i, suberror in enumerate(sorted(error.context, key=lambda e: e.schema_path)):
schema_location = " -> ".join(str(p) for p in suberror.schema_path)
data_location = " -> ".join(str(p) for p in suberror.absolute_path) if suberror.absolute_path else "root"
print(f" Option {i}: {schema_location} | {suberror.message} | Failed at: {data_location}")
else:
# Handle non-anyOf errors normally
print(f"{error.absolute_path}: {error.message}")
You can also group the context errors by which anyOf option they came from:
python
from collections import defaultdict
for error in errors:
if error.validator == 'anyOf' and error.context:
# Group errors by which anyOf option they belong to
errors_by_option = defaultdict(list)
for suberror in error.context:
# The first element of schema_path after 'anyOf' tells us which option
if len(suberror.schema_path) > 1 and suberror.schema_path[0] == 'anyOf':
option_index = suberror.schema_path[1]
errors_by_option[option_index].append(suberror)
# Show the option with fewest errors (closest match)
best_option = min(errors_by_option.keys(), key=lambda k: len(errors_by_option[k]))
print(f"Closest match was anyOf option {best_option}:")
for suberror in errors_by_option[best_option]:
print(f" {suberror.message}")
This is definitely the cleanest approach - using the built-in context attribute rather than re-implementing the validation logic yourself.
User
Given that, when iterating the errors, I see the schema_path seems to contain [, ]. It seems like the best match is the one where there are the fewest errors for that initial number. How can I select the first suberror where the schema_path has the fewest validation errors?
Assistant
You can group the suberrors by their first schema_path element (the anyOf option index) and find the option with the fewest errors:
python
from collections import defaultdict
for error in errors:
if error.validator == 'anyOf' and error.context:
# Group suberrors by anyOf option index (first element of schema_path)
errors_by_option = defaultdict(list)
for suberror in error.context:
if suberror.schema_path:
option_index = suberror.schema_path[0]
errors_by_option[option_index].append(suberror)
# Find the option with fewest errors (best match)
best_option_index = min(errors_by_option.keys(),
key=lambda k: len(errors_by_option[k]))
# Get the first suberror from the best matching option
best_match_errors = errors_by_option[best_option_index]
first_error_from_best_match = best_match_errors[0]
print(f"Best match is anyOf option {best_option_index} with {len(best_match_errors)} errors")
print(f"First error: {first_error_from_best_match.message}")
print(f"Schema path: {list(first_error_from_best_match.schema_path)}")
Or if you want a more concise version that just gets the first suberror from the best matching option:
python
for error in errors:
if error.validator == 'anyOf' and error.context:
# Group by option index and find the one with fewest errors
from collections import defaultdict
by_option = defaultdict(list)
for suberror in error.context:
if suberror.schema_path:
by_option[suberror.schema_path[0]].append(suberror)
# Get first suberror from the option with fewest total errors
best_option = min(by_option.keys(), key=lambda k: len(by_option[k]))
first_best_error = by_option[best_option][0]
print(f"Closest match error: {first_best_error.message}")
This will give you the first validation error from whichever anyOf option had the fewest total validation failures, which should represent the "closest match" to what your data was trying to be.
User
Can we use jsonschema.exceptions.best_match to get the appropriate error?
Assistant
Yes! jsonschema.exceptions.best_match is exactly what you want - it's designed specifically for this use case. It automatically finds the most relevant error from a set of validation errors, including handling anyOf scenarios intelligently.
python
import jsonschema
from jsonschema.exceptions import best_match
try:
jsonschema.validate(data, schema)
except jsonschema.ValidationError as e:
# Get all validation errors
validator = jsonschema.Draft7Validator(schema)
errors = list(validator.iter_errors(data))
# Find the best match
best_error = best_match(errors)
if best_error:
print(f"Most relevant error: {best_error.message}")
print(f"Field path: {'.'.join(str(x) for x in best_error.absolute_path)}")
print(f"Failed value: {best_error.instance}")
Or even simpler, you can use it directly with the context of an anyOf error:
python
try:
jsonschema.validate(data, schema)
except jsonschema.ValidationError as e:
if e.validator == 'anyOf' and e.context:
best_error = best_match(e.context)
print(f"Best match error: {best_error.message}")
else:
print(f"Error: {e.message}")
The best_match function uses heuristics to determine which error is most "relevant" - it considers factors like:
How deep in the schema the error occurred
The type of validation that failed
The specificity of the constraint
This is much cleaner than manually grouping by schema path and counting errors, and it's the official jsonschema way to handle this exact problem. The function is specifically designed to pick the most actionable error from a set of validation failures.
def analyze_validation_errors(data, schema, path=""):
"""Recursively analyze validation errors, handling anyOf specially"""
if 'anyOf' in schema:
best_errors = []
min_error_count = float('inf')
for i, sub_schema in enumerate(schema['anyOf']):
validator = jsonschema.Draft7Validator(sub_schema)
errors = list(validator.iter_errors(data))
if len(errors) < min_error_count:
min_error_count = len(errors)
best_errors = [(f"anyOf[{i}]", errors)]
elif len(errors) == min_error_count:
best_errors.append((f"anyOf[{i}]", errors))
return best_errors
else:
validator = jsonschema.Draft7Validator(schema)
errors = list(validator.iter_errors(data))
return [("direct", errors)]
# Usage
results = analyze_validation_errors(data, schema)
for option_name, errors in results:
print(f"\nBest match ({option_name}):")
for error in errors:
field = ".".join(str(x) for x in error.absolute_path) or "root"
print(f" {field}: {error.message} (got: {repr(error.instance)})")
Create a "diff-style" comparison
python
def compare_with_anyof_options(data, schema):
"""Show how the data differs from each anyOf option"""
if 'anyOf' not in schema:
return None
results = []
for i, sub_schema in enumerate(schema['anyOf']):
validator = jsonschema.Draft7Validator(sub_schema)
errors = list(validator.iter_errors(data))
# Summarize what this option expects vs what we got
summary = {
'option': i,
'expected_type': sub_schema.get('type', 'any'),
'error_summary': [],
'total_errors': len(errors)
}
for error in errors:
field = ".".join(str(x) for x in error.absolute_path) or "root"
summary['error_summary'].append({
'field': field,
'expected': error.validator_value,
'got': error.instance,
'rule': error.validator
})
results.append(summary)
# Sort by best match (fewest errors)
results.sort(key=lambda x: x['total_errors'])
return results
# Usage
comparisons = compare_with_anyof_options(data, schema)
if comparisons:
print("Validation failed. Here's how your data compares to each option:\n")
for comp in comparisons:
print(f"Option {comp['option']} (expects {comp['expected_type']}) - {comp['total_errors']} errors:")
for err in comp['error_summary']:
print(f" {err['field']}: expected {err['rule']}={err['expected']}, got {repr(err['got'])}")
print()
The key insight is that you need to manually validate against each anyOf option separately to see which one came closest to matching, rather than relying on jsonschema's built-in anyOf validation which just tells you "none worked."