import json
def validate_json(json_data, schema):
"""
Validates a JSON object against a given schema.
Args:
json_data (dict): The JSON object to validate.
schema (dict): The schema to validate against.
Returns:
list: A list of flagged anomalies (error messages). Empty list if valid.
"""
anomalies = []
def check_type(value, expected_type):
"""Checks if a value matches the expected type."""
if type(value) != expected_type:
return f"Type mismatch: Expected {expected_type}, got {type(value)}"
return None
def check_required_fields(data, schema):
"""Checks for missing required fields."""
for key, value in schema.items():
if key not in data:
return f"Missing required field: {key}"
return None
def check_value_constraints(value, constraints):
"""Checks if a value meets specific constraints."""
if constraints:
for constraint_type, constraint_value in constraints.items():
if constraint_type == "min":
if not isinstance(value, (int, float)) or value < constraint_value:
return f"Value {key} must be >= {constraint_value}"
elif constraint_type == "max":
if not isinstance(value, (int, float)) or value > constraint_value:
return f"Value {key} must be <= {constraint_value}"
elif constraint_type == "in":
if value not in constraint_value:
return f"Value {key} must be one of: {constraint_value}"
return None
# Check required fields
required_error = check_required_fields(json_data, schema)
if required_error:
anomalies.append(required_error)
# Check data types
for key, value in schema.items():
if key in json_data:
if isinstance(value, dict):
if not isinstance(json_data[key], dict):
anomalies.append(f"Type mismatch for {key}: Expected dict, got {type(json_data[key])}")
continue
else:
nested_errors = validate_json(json_data[key], value)
anomalies.extend(nested_errors)
elif isinstance(value, list):
if not isinstance(json_data[key], list):
anomalies.append(f"Type mismatch for {key}: Expected list, got {type(json_data[key])}")
continue
else:
for i, item in enumerate(json_data[key]):
if isinstance(value[i], dict):
if not isinstance(item, dict):
anomalies.append(f"Type mismatch for item in list {key} at index {i}: Expected dict, got {type(item)}")
elif isinstance(value[i], list):
anomalies.append(f"Type mismatch for item in list {key} at index {i}: Expected list, got {type(item)}")
else:
continue #ignore simple types
else:
error = check_type(json_data[key], value)
if error:
anomalies.append(error)
return anomalies
if __name__ == '__main__':
# Example Usage
schema = {
"name": str,
"age": int,
"city": str,
"scores": list,
"details": {
"height": float,
"weight": float
}
}
valid_json = {
"name": "Alice",
"age": 30,
"city": "New York",
"scores": [85, 90, 92],
"details": {
"height": 1.75,
"weight": 60.0
}
}
invalid_json = {
"name": 123,
"age": "thirty",
"scores": "not a list",
"details": {
"height": "tall",
"weight": -10.0
}
}
print("
Add your comment