Created
November 1, 2024 14:31
-
-
Save RockinPaul/373fd94ef5541343f4b54ff9b5e0aae1 to your computer and use it in GitHub Desktop.
json_validator.py - Validate multiple JSON files at once with this Python CLI script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import sys | |
import os | |
from pathlib import Path | |
from typing import Dict, List, Tuple | |
""" | |
Validate multiple json files at once. | |
In Terminal call: | |
python json_validator.py /path/to/directory/with/jsons | |
""" | |
def validate_json_file(file_path: Path) -> Tuple[bool, str]: | |
""" | |
Validate a single JSON file. | |
Returns a tuple of (is_valid, error_message) | |
""" | |
print(f"Validating file: {file_path}") # Debug print | |
try: | |
with open(file_path, 'r', encoding='utf-8') as f: | |
content = f.read() | |
if not content.strip(): | |
return False, "File is empty" | |
json.loads(content) # Using loads instead of load | |
return True, "Valid JSON" | |
except json.JSONDecodeError as e: | |
return False, f"Invalid JSON: {str(e)}" | |
except Exception as e: | |
return False, f"Error reading file: {str(e)}" | |
def validate_json_files(folder_path: str) -> Dict[str, List[str]]: | |
""" | |
Validate all JSON files in the specified folder and its subfolders. | |
Returns a dictionary with lists of valid and invalid files. | |
""" | |
results = { | |
'valid': [], | |
'invalid': [] | |
} | |
try: | |
folder = Path(folder_path).resolve() # Get absolute path | |
print(f"Checking folder: {folder}") # Debug print | |
if not folder.exists(): | |
print(f"Error: Folder '{folder_path}' does not exist") | |
sys.exit(1) | |
if not folder.is_dir(): | |
print(f"Error: '{folder_path}' is not a directory") | |
sys.exit(1) | |
# Find all .json files recursively | |
print("Searching for JSON files...") # Debug print | |
json_files = list(folder.rglob("*.json")) | |
if not json_files: | |
print(f"No JSON files found in '{folder_path}'") | |
sys.exit(0) | |
print(f"Found {len(json_files)} JSON files. Validating...") | |
print("Files found:", *[str(f) for f in json_files], sep='\n- ') # List all found files | |
for file_path in json_files: | |
is_valid, error_message = validate_json_file(file_path) | |
try: | |
relative_path = file_path.relative_to(folder) | |
except ValueError: | |
relative_path = file_path # Fallback to full path if relative path fails | |
if is_valid: | |
results['valid'].append(str(relative_path)) | |
else: | |
results['invalid'].append(f"{relative_path}: {error_message}") | |
except Exception as e: | |
print(f"Unexpected error: {str(e)}") | |
sys.exit(1) | |
return results | |
def main(): | |
print("Starting JSON validator...") # Debug print | |
if len(sys.argv) != 2: | |
print("Usage: python json_validator.py <folder_path>") | |
sys.exit(1) | |
folder_path = sys.argv[1] | |
print(f"Input folder path: {folder_path}") # Debug print | |
results = validate_json_files(folder_path) | |
# Print results | |
print("\n=== Validation Results ===") | |
print(f"\nValid JSON files ({len(results['valid'])}):") | |
for file in results['valid']: | |
print(f"✅ {file}") | |
print(f"\nInvalid JSON files ({len(results['invalid'])}):") | |
for file in results['invalid']: | |
print(f"❌ {file}") | |
# Print summary | |
total = len(results['valid']) + len(results['invalid']) | |
print(f"\nSummary:") | |
print(f"Total files: {total}") | |
print(f"Valid: {len(results['valid'])}") | |
print(f"Invalid: {len(results['invalid'])}") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment