Files
troupe-standup/wizard-work/spark/json_validate_standalone.py
T

71 lines
1.9 KiB
Python

#!/usr/bin/env python3
"""JSON Validator CLI - Validates JSON files and reports syntax errors."""
import json
import sys
from pathlib import Path
def validate_json_file(filepath: str) -> dict:
"""Validate a JSON file and return result dict."""
result = {
"file": filepath,
"valid": False,
"error": None,
"line": None,
"column": None,
"decoded": None
}
try:
content = Path(filepath).read_text()
except FileNotFoundError:
result["error"] = f"File not found: {filepath}"
return result
except Exception as e:
result["error"] = f"Read error: {e}"
return result
try:
data = json.loads(content)
result["valid"] = True
result["decoded"] = data
return result
except json.JSONDecodeError as e:
result["error"] = str(e.msg)
result["line"] = e.lineno
result["column"] = e.colno
# Show context around error
lines = content.split('\n')
if e.lineno and e.lineno <= len(lines):
result["context"] = lines[e.lineno - 1]
return result
def main():
if len(sys.argv) < 2:
print("Usage: json_validate_standalone.py <file.json> [file2.json...]")
sys.exit(1)
exit_code = 0
results = []
for filepath in sys.argv[1:]:
result = validate_json_file(filepath)
results.append(result)
if result["valid"]:
print(f"VALID: {filepath}")
else:
print(f"INVALID: {filepath}")
print(f" Error: {result['error']}")
if result.get('line'):
print(f" Line: {result['line']}, Column: {result['column']}")
if result.get('context'):
print(f" Context: {result['context'][:60]}")
exit_code = 1
sys.exit(exit_code)
if __name__ == "__main__":
main()