Files
troupe-standup/wizard-work/spark/validate_json_schema.py

45 lines
1.4 KiB
Python

#!/usr/bin/env python3
"""Quick JSON schema validator: validates a JSON file against a schema file.
Usage: python validate_json_schema.py <data.json> <schema.json>
Exit 0 if valid, 1 if invalid, 2 on error.
Example:
echo '{"type":"object","properties":{"name":{"type":"string"}}}' > schema.json
echo '{"name":"test"}' > data.json
python validate_json_schema.py data.json schema.json # exits 0
"""
import json
import sys
from jsonschema import validate, ValidationError, SchemaError
def main():
if len(sys.argv) < 3:
print("Usage: validate_json_schema.py <data.json> <schema.json>", file=sys.stderr)
sys.exit(2)
try:
with open(sys.argv[1], 'r') as f:
data = json.load(f)
with open(sys.argv[2], 'r') as f:
schema = json.load(f)
except FileNotFoundError as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(2)
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON - {e}", file=sys.stderr)
sys.exit(2)
try:
validate(instance=data, schema=schema)
print("Valid: JSON conforms to schema")
sys.exit(0)
except ValidationError as e:
print(f"Invalid: {e.message}", file=sys.stderr)
sys.exit(1)
except SchemaError as e:
print(f"Invalid schema: {e.message}", file=sys.stderr)
sys.exit(2)
if __name__ == "__main__":
main()