#!/usr/bin/env python3 """Simple JSON validator CLI - validates JSON files and reports errors.""" import json import sys from pathlib import Path def validate_json_file(filepath: str) -> tuple[bool, str]: """Validate a JSON file. Returns: (True, "") if valid (False, error_message) if invalid """ try: with open(filepath, 'r') as f: json.load(f) return True, "" except FileNotFoundError: return False, f"Error: File not found: {filepath}" except json.JSONDecodeError as e: return False, f"Error: Invalid JSON at line {e.lineno}, column {e.colno}: {e.msg}" except Exception as e: return False, f"Error reading file: {e}" def validate_json_directory(directory: str) -> dict: """Validate all .json files in a directory. 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 = list(dir_path.glob("*.json")) valid = 0 invalid = 0 for jf in json_files: is_valid, _ = validate_json_file(str(jf)) if is_valid: valid += 1 else: invalid += 1 return {"total": len(json_files), "valid": valid, "invalid": invalid} def main(): if len(sys.argv) < 2: print("Usage: json_validator.py [file2.json] ...", file=sys.stderr) print(" json_validator.py --dir ", file=sys.stderr) sys.exit(1) # Check for --dir flag if "--dir" in sys.argv: try: dir_idx = sys.argv.index("--dir") directory = sys.argv[dir_idx + 1] result = validate_json_directory(directory) if "error" in result and result.get("total") == 0: print(f"Error: {result['error']}", file=sys.stderr) sys.exit(1) print(f"Directory: {directory}") print(f"Total: {result['total']}") print(f"Valid: {result['valid']}") print(f"Invalid: {result['invalid']}") sys.exit(result['invalid']) except IndexError: print("Error: --dir requires a directory argument", file=sys.stderr) sys.exit(1) else: files = sys.argv[1:] all_valid = True results = [] for filepath in files: valid, error = validate_json_file(filepath) if valid: results.append(f"VALID: {filepath}") else: results.append(f"INVALID: {filepath} - {error}") all_valid = False for r in results: print(r) sys.exit(0 if all_valid else 1) if __name__ == "__main__": main()