Files

40 lines
1.2 KiB
Python

#!/usr/bin/env python3
"""JSON validator and formatter utility.
Usage: python json_validate.py <file.json
Tests validity and outputs formatted JSON with line count.
"""
import json
import sys
from pathlib import Path
def validate_and_format(filepath: str) -> dict:
"""Validate JSON file and return formatted output."""
path = Path(filepath)
if not path.exists():
return {"valid": False, "error": f"File not found: {filepath}", "lines": 0}
try:
with open(path, 'r') as f:
data = json.load(f)
formatted = json.dumps(data, indent=2, sort_keys=True)
lines = len(formatted.split('\n'))
return {"valid": True, "lines": lines, "content": formatted}
except json.JSONDecodeError as e:
return {"valid": False, "error": str(e), "lines": 0}
except Exception as e:
return {"valid": False, "error": str(e), "lines": 0}
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python json_validate.py <file.json>")
sys.exit(1)
result = validate_and_format(sys.argv[1])
if not result["valid"]:
print(f"INVALID: {result['error']}")
sys.exit(1)
print(f"VALID: {result['lines']} lines")
print(result["content"])