import json
from typing import Dict, Any, List, Optional
from jsonschema import validate, ValidationError, Draft7Validator
import sys
def validate_json_data(data: Dict[str, Any], schema: Dict[str, Any]) -> Dict[str, Any]:
"""
Validate JSON data against a schema and return validation results.
Args:
data: JSON data to validate
schema: JSON schema to validate against
Returns:
Dictionary containing validation results with 'valid' and 'errors' keys
"""
try:
# Validate the data against the schema
validate(instance=data, schema=schema)
return {
"valid": True,
"errors": []
}
except ValidationError as e:
return {
"valid": False,
"errors": [
{
"message": e.message,
"path": list(e.absolute_path),
"schema_path": list(e.absolute_schema_path)
}
]
}
except Exception as e:
return {
"valid": False,
"errors": [
{
"message": f"Validation error: {str(e)}",
"path": [],
"schema_path": []
}
]
}
def validate_multiple_schemas(data: Dict[str, Any], schemas: List[Dict[str, Any]]) -> Dict[str, Any]:
"""
Validate JSON data against multiple schemas and return combined results.
Args:
data: JSON data to validate
schemas: List of JSON schemas to validate against
Returns:
Dictionary containing validation results
"""
all_errors = []
valid = True
for i, schema in enumerate(schemas):
try:
validate(instance=data, schema=schema)
except ValidationError as e:
valid = False
all_errors.append({
"schema_index": i,
"message": e.message,
"path": list(e.absolute_path),
"schema_path": list(e.absolute_schema_path)
})
except Exception as e:
valid = False
all_errors.append({
"schema_index": i,
"message": f"Validation error: {str(e)}",
"path": [],
"schema_path": []
})
return {
"valid": valid,
"errors": all_errors
}
def create_user_schema() -> Dict[str, Any]:
"""Create a sample schema for user data validation."""
return {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"email": {
"type": "string",
"format": "email"
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 150
},
"address": {
"type": "object",
"properties": {
"street": {"type": "string"},
"city": {"type": "string"},
"zipcode": {"type": "string", "pattern": "^[0-9]{5}(?:-[0-9]{4})?$"}
},
"required": ["street", "city"]
},
"interests": {
"type": "array",
"items": {"type": "string"}
}
},
"required": ["name", "email"],
"additionalProperties": False
}
def main():
"""Example usage of the JSON validator."""
# Sample user data
user_data = {
"name": "John Doe",
"email": "john.doe@example.com",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"zipcode": "12345"
},
"interests": ["programming", "reading", "hiking"]
}
# Sample invalid user data
invalid_user_data = {
"name": "",
"email": "invalid-email",
"age": -5,
"address": {
"city": "Anytown"
},
"interests": ["reading", 123]
}
# Create schema
schema = create_user_schema()
# Validate valid data
print("Validating valid user data:")
result = validate_json_data(user_data, schema)
print(f"Valid: {result['valid']}")
if result['errors']:
for error in result['errors']:
print(f" Error: {error['message']}")
else:
print(" No errors found")
print("\nValidating invalid user data:")
result = validate_json_data(invalid_user_data, schema)
print(f"Valid: {result['valid']}")
for error in result['errors']:
print(f" Error: {error['message']}")
print(f" Path: {' -> '.join(map(str, error['path'])) if error['path'] else 'root'}")
# Example of validating against multiple schemas
print("\n\nValidating against multiple schemas:")
schema1 = create_user_schema()
schema2 = {
"type": "object",
"properties": {
"name": {"type": "string", "minLength": 5}
},
"required": ["name"]
}
# This will validate against both schemas
result = validate_multiple_schemas(user_data, [schema1, schema2])
print(f"Valid against all schemas: {result['valid']}")
if result['errors']:
for error in result['errors']:
print(f" Schema {error['schema_index']}: {error['message']}")
else:
print(" No errors found")
if __name__ == "__main__":
# Install required package if not already installed
try:
import jsonschema
except ImportError:
print("Please install jsonschema: pip install jsonschema")
sys.exit(1)
main()
This Python snippet provides a robust JSON data validator that uses the jsonschema
library to validate JSON data against defined schemas. It includes two main functions:
validate_json_data
: Validates a single JSON object against a schemavalidate_multiple_schemas
: Validates data against multiple schemas simultaneouslyThe code includes a helper function to create a user schema for demonstration purposes, which validates common user data with properties like name, email, age, and address.
JSON validation is crucial when working with APIs, configuration files, and data storage. This snippet helps ensure:
pip install jsonschema
python json_validator.py
data = {“name”: “John”, “email”: “john@example.com”} schema = create_user_schema() result = validate_json_data(data, schema) ```
The script will output validation results for both valid and invalid data examples, showing how to identify and handle validation errors.