52 lines
1.2 KiB
Python
52 lines
1.2 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
json_syntax_checker.py - Minimal JSON syntax validator.
|
|
|
|
Verifies JSON files are syntactically correct.
|
|
Exit 0 = valid JSON, Exit 1 = invalid JSON
|
|
"""
|
|
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
def check_json_syntax(file_path: str) -> tuple[bool, str]:
|
|
"""Check if file contains valid JSON.
|
|
|
|
Returns: (is_valid, message)
|
|
"""
|
|
path = Path(file_path)
|
|
|
|
if not path.exists():
|
|
return False, f"File not found: {file_path}"
|
|
|
|
try:
|
|
content = path.read_text().strip()
|
|
|
|
if not content:
|
|
return False, "Empty file"
|
|
|
|
json.loads(content)
|
|
return True, "Valid JSON"
|
|
|
|
except json.JSONDecodeError as e:
|
|
return False, f"JSON error at line {e.lineno}, col {e.colno}: {e.msg}"
|
|
except Exception as e:
|
|
return False, f"Error: {e}"
|
|
|
|
|
|
def main():
|
|
if len(sys.argv) < 2:
|
|
print("Usage: json_syntax_checker.py <json_file>")
|
|
sys.exit(1)
|
|
|
|
file_path = sys.argv[1]
|
|
is_valid, message = check_json_syntax(file_path)
|
|
|
|
print(f"{message}")
|
|
sys.exit(0 if is_valid else 1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |