42 lines
1.0 KiB
Python
42 lines
1.0 KiB
Python
#!/usr/bin/env python3
|
|
"""JSON Lint CLI - validates JSON from stdin or --text flag."""
|
|
|
|
import json
|
|
import sys
|
|
|
|
|
|
def validate(text: str) -> tuple[bool, str]:
|
|
"""Validate JSON text. Returns (is_valid, error_msg)."""
|
|
try:
|
|
json.loads(text)
|
|
return True, ""
|
|
except json.JSONDecodeError as e:
|
|
return False, f"Line {e.lineno}, Col {e.colno}: {e.msg}"
|
|
|
|
|
|
def main():
|
|
if len(sys.argv) == 3 and sys.argv[1] == "--text":
|
|
# Validate inline JSON text
|
|
text = sys.argv[2]
|
|
elif len(sys.argv) == 2 and sys.argv[1] == "-":
|
|
# Validate from stdin
|
|
text = sys.stdin.read()
|
|
elif len(sys.argv) == 2:
|
|
# Validate from file path
|
|
with open(sys.argv[1], 'r') as f:
|
|
text = f.read()
|
|
else:
|
|
print("Usage: jsonlint.py [--text 'json'] | [-]", file=sys.stderr)
|
|
sys.exit(2)
|
|
|
|
ok, err = validate(text)
|
|
if ok:
|
|
print("VALID")
|
|
sys.exit(0)
|
|
else:
|
|
print(f"INVALID: {err}", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |