Files
troupe-standup/wizard-work/spark/json_key_validator.py
T

50 lines
1.4 KiB
Python

#!/usr/bin/env python3
"""
JSON Key Validator - Verifies JSON files contain expected keys.
Usage: python json_key_validator.py <json_file> <key1,key2,...>
Exit 0: all keys present
Exit 1: missing keys
Exit 2: file error
"""
import sys
import json
def validate_json_keys(filepath: str, expected_keys: list) -> tuple[bool, list]:
"""Validate that a JSON file contains all expected keys."""
with open(filepath, 'r') as f:
data = json.load(f)
if not isinstance(data, dict):
return False, ["JSON root is not an object"]
missing = [k for k in expected_keys if k not in data]
return len(missing) == 0, missing
def main():
if len(sys.argv) != 3:
print("Usage: python json_key_validator.py <json_file> <key1,key2,...>")
sys.exit(2)
filepath = sys.argv[1]
expected_keys = [k.strip() for k in sys.argv[2].split(',')]
try:
valid, missing = validate_json_keys(filepath, expected_keys)
if valid:
print(f"PASS: All {len(expected_keys)} keys present in {filepath}")
sys.exit(0)
else:
print(f"FAIL: Missing keys in {filepath}: {missing}")
sys.exit(1)
except FileNotFoundError:
print(f"ERROR: File not found: {filepath}")
sys.exit(2)
except json.JSONDecodeError as e:
print(f"ERROR: Invalid JSON: {e}")
sys.exit(2)
if __name__ == "__main__":
main()