#!/usr/bin/env python3 """Enhanced JSON Validator - validates JSON files with proper exit codes. Exit 0: All valid Exit 1: One or more inputs could not be validated (invalid JSON, schema mismatch) Exit 2: Usage error (bad arguments, a path that does not exist, unusable schema) The exit code reports the *outcome of the request*, never a count: `--dir` mode exits 1 when any file in the directory is invalid, however many that is (a count as an exit status silently reads as success at 256 and as a usage error at 2). The per-run summary lines carry the counts. Features: - Validate individual files: json-validator.py ... - Validate directory: json-validator.py --dir - Error reporting with file paths, one INVALID line per failing file - Schema validation support via --schema flag - --quiet suppresses the VALID banner for passing files Requires no third-party package unless --schema is used (then: jsonschema). """ import sys import json import argparse from pathlib import Path def validate_json_file(filepath: str, schema: dict | None = None, quiet: bool = False) -> tuple[bool, str]: """Validate a JSON file. Args: filepath: Path to the JSON file schema: Optional JSON schema dict for schema validation quiet: Suppress the VALID line for a passing file 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) if not quiet: print(f"VALID: {filepath}") return True, "" except json.JSONDecodeError as e: return False, f"Invalid JSON at line {e.lineno}, column {e.colno}: {e.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 = None, quiet: bool = False) -> dict: """Validate every .json file in a directory (non-recursive). Args: directory: Path to directory schema: Optional JSON schema for validation quiet: Suppress the VALID lines for passing files Returns: Dict with totals and counts, or {"error": ...} when the directory is unusable """ 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, quiet) 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 exit_code_for(invalid: int) -> int: """Map an invalid-input count onto the documented exit contract (0 or 1). Never returns the count itself: an exit status is a class, not a tally. """ return 0 if invalid == 0 else 1 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', encoding='utf-8') as f: schema = json.load(f) except Exception as e: print(f"Error loading schema: {e}", file=sys.stderr) sys.exit(2) try: import jsonschema # noqa: F401 except ImportError: print("Error: --schema requires the jsonschema package, which is not importable", file=sys.stderr) sys.exit(2) if args.directory: result = validate_json_directory(args.directory, schema, args.quiet) 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(exit_code_for(result['invalid'])) invalid = 0 missing = 0 for path in args.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, args.quiet) if not is_valid: invalid += 1 print(f"INVALID: {json_file} - {error}") elif p.is_file(): is_valid, error = validate_json_file(str(p), schema, args.quiet) if not is_valid: invalid += 1 print(f"INVALID: {p} - {error}") else: print(f"NOT FOUND: {path}", file=sys.stderr) missing += 1 if missing: # A path that does not exist is a bad invocation, not bad data. sys.exit(2) sys.exit(exit_code_for(invalid)) if __name__ == "__main__": main()