#!/usr/bin/env python3 """json_tool.py - Quick JSON formatter and validator for CLI. Usage: echo '{"a":1}' | python3 json_tool.py python3 json_tool.py < file.json python3 json_tool.py --validate file.json # just validate """ import sys, json, argparse def main(): parser = argparse.ArgumentParser(description='Format/validate JSON') parser.add_argument('file', nargs='?', help='JSON file to process') parser.add_argument('--validate', action='store_true', help='Only validate, no output') args = parser.parse_args() try: if args.file: content = open(args.file).read() else: content = sys.stdin.read() data = json.loads(content) if args.validate: print("VALID", file=sys.stderr) else: print(json.dumps(data, indent=2, sort_keys=True)) except json.JSONDecodeError as e: print(f"INVALID: {e}", file=sys.stderr) sys.exit(1) except Exception as e: print(f"ERROR: {e}", file=sys.stderr) sys.exit(1) if __name__ == '__main__': main()