145 lines
4.4 KiB
Python
145 lines
4.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Enhanced JSON Validator - validates JSON files with proper exit codes.
|
|
|
|
Exit 0: All valid
|
|
Exit 1: One or more invalid
|
|
Exit 2: Usage error
|
|
|
|
Features:
|
|
- Validate individual files: json-validator.py <file.json> ...
|
|
- Validate directory: json-validator.py --dir <directory>
|
|
- Returns count of invalid files as exit code for --dir mode
|
|
- Enhanced error reporting with file paths
|
|
- JSON syntax highlighting support
|
|
- Schema validation support via --schema flag
|
|
"""
|
|
|
|
import sys
|
|
import json
|
|
import argparse
|
|
from pathlib import Path
|
|
|
|
|
|
def validate_json_file(filepath: str, schema: dict = None) -> tuple[bool, str]:
|
|
"""Validate a JSON file.
|
|
|
|
Args:
|
|
filepath: Path to the JSON file
|
|
schema: Optional JSON schema dict for schema validation
|
|
|
|
Returns:
|
|
(True, "") if valid
|
|
(False, error_message) if invalid
|
|
"""
|
|
try:
|
|
with open(filepath, 'r', encoding='utf-8') as f:
|
|
data = json.load(f)
|
|
|
|
if schema:
|
|
import jsonschema
|
|
jsonschema.validate(instance=data, schema=schema)
|
|
|
|
print(f"VALID: {filepath}")
|
|
return True, ""
|
|
except json.JSONDecodeError as e:
|
|
error_msg = f"Invalid JSON at line {e.lineno}, column {e.colno}: {e.msg}"
|
|
return False, error_msg
|
|
except FileNotFoundError:
|
|
return False, "File not found"
|
|
except Exception as e:
|
|
return False, f"Error: {e}"
|
|
|
|
|
|
def validate_json_directory(directory: str, schema: dict = None) -> dict:
|
|
"""Validate all .json files in a directory.
|
|
|
|
Args:
|
|
directory: Path to directory
|
|
schema: Optional JSON schema for validation
|
|
|
|
Returns:
|
|
Dict with totals and counts
|
|
"""
|
|
dir_path = Path(directory)
|
|
if not dir_path.exists():
|
|
return {"error": f"Directory not found: {directory}", "total": 0, "valid": 0, "invalid": 0}
|
|
if not dir_path.is_dir():
|
|
return {"error": f"Not a directory: {directory}", "total": 0, "valid": 0, "invalid": 0}
|
|
|
|
json_files = sorted(dir_path.glob("*.json"))
|
|
valid = 0
|
|
invalid = 0
|
|
invalid_files = []
|
|
|
|
for jf in json_files:
|
|
is_valid, error = validate_json_file(str(jf), schema)
|
|
if is_valid:
|
|
valid += 1
|
|
else:
|
|
invalid += 1
|
|
invalid_files.append((jf.name, error))
|
|
print(f"INVALID: {jf.name} - {error}")
|
|
|
|
return {
|
|
"total": len(json_files),
|
|
"valid": valid,
|
|
"invalid": invalid,
|
|
"invalid_files": invalid_files[:10]
|
|
}
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description='Enhanced JSON Validator')
|
|
parser.add_argument('paths', nargs='*', help='JSON files or directories to validate')
|
|
parser.add_argument('--dir', dest='directory', help='Directory to validate')
|
|
parser.add_argument('--schema', help='JSON Schema file for validation')
|
|
parser.add_argument('--quiet', '-q', action='store_true', help='Suppress VALID messages')
|
|
|
|
args = parser.parse_args()
|
|
|
|
if not args.paths and not args.directory:
|
|
parser.print_help()
|
|
sys.exit(2)
|
|
|
|
schema = None
|
|
if args.schema:
|
|
try:
|
|
with open(args.schema, 'r') as f:
|
|
schema = json.load(f)
|
|
except Exception as e:
|
|
print(f"Error loading schema: {e}", file=sys.stderr)
|
|
sys.exit(2)
|
|
|
|
if args.directory:
|
|
result = validate_json_directory(args.directory, schema)
|
|
if "error" in result:
|
|
print(f"Error: {result['error']}", file=sys.stderr)
|
|
sys.exit(2)
|
|
print(f"\nDirectory: {args.directory}")
|
|
print(f"Total: {result['total']}")
|
|
print(f"Valid: {result['valid']}")
|
|
print(f"Invalid: {result['invalid']}")
|
|
sys.exit(result['invalid'])
|
|
else:
|
|
paths = args.paths
|
|
all_valid = True
|
|
for path in paths:
|
|
p = Path(path)
|
|
if p.is_dir():
|
|
for json_file in sorted(p.rglob("*.json")):
|
|
is_valid, error = validate_json_file(str(json_file), schema)
|
|
if not is_valid:
|
|
all_valid = False
|
|
elif p.is_file():
|
|
is_valid, error = validate_json_file(str(p), schema)
|
|
if not is_valid:
|
|
all_valid = False
|
|
else:
|
|
print(f"NOT FOUND: {path}", file=sys.stderr)
|
|
all_valid = False
|
|
|
|
sys.exit(0 if all_valid else 1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |