37 lines
1.2 KiB
Python
37 lines
1.2 KiB
Python
#!/usr/bin/env python3
|
|
"""JSON linter: validates and pretty-prints JSON files with structured output."""
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
def validate_json_file(filepath: str) -> dict:
|
|
"""Validate a JSON file and return structured result."""
|
|
result = {"file": filepath, "valid": False, "error": None, "type": None, "keys": []}
|
|
|
|
try:
|
|
content = Path(filepath).read_text()
|
|
data = json.loads(content)
|
|
result["valid"] = True
|
|
result["type"] = type(data).__name__
|
|
|
|
if isinstance(data, dict):
|
|
result["keys"] = sorted(data.keys())
|
|
elif isinstance(data, list):
|
|
result["length"] = len(data)
|
|
except FileNotFoundError:
|
|
result["error"] = "File not found"
|
|
except json.JSONDecodeError as e:
|
|
result["error"] = f"JSON parse error at line {e.lineno}, col {e.colno}: {e.msg}"
|
|
except Exception as e:
|
|
result["error"] = str(e)
|
|
|
|
return result
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) < 2:
|
|
print(json.dumps({"error": "Usage: json_lint.py <file.json>"}))
|
|
sys.exit(1)
|
|
|
|
result = validate_json_file(sys.argv[1])
|
|
print(json.dumps(result, indent=2))
|
|
sys.exit(0 if result["valid"] else 1) |