#!/usr/bin/env python3 """Simple JSON prettifier for command-line use.""" import json import sys import argparse def main(): parser = argparse.ArgumentParser( description="Pretty-print JSON from file or stdin", epilog="Examples:\n" " json-pretty input.json\n" " cat data.json | json-pretty\n" " json-pretty input.json -o output.json\n" " echo '{\"a\":1}' | json-pretty --indent 4", formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument( 'input', nargs='?', help='Input JSON file (omit or use - for stdin)' ) parser.add_argument( '-o', '--output', help='Output file (default: stdout)' ) parser.add_argument( '-i', '--indent', type=int, default=2, help='Indentation spaces (default: 2)' ) parser.add_argument( '-s', '--sort-keys', action='store_true', help='Sort object keys alphabetically' ) parser.add_argument( '-c', '--compact', action='store_true', help='Compact output (no extra whitespace)' ) args = parser.parse_args() # Read input try: if args.input and args.input != '-': with open(args.input, 'r') as f: input_text = f.read() else: input_text = sys.stdin.read() except FileNotFoundError: print(f"Error: File '{args.input}' not found", file=sys.stderr) sys.exit(1) except Exception as e: print(f"Error reading input: {e}", file=sys.stderr) sys.exit(1) # Parse and format JSON try: data = json.loads(input_text) if args.compact: output = json.dumps(data, sort_keys=args.sort_keys, separators=(',', ':')) else: output = json.dumps(data, indent=args.indent, sort_keys=args.sort_keys) except json.JSONDecodeError as e: print(f"Error: Invalid JSON - {e}", file=sys.stderr) sys.exit(1) # Write output try: if args.output: with open(args.output, 'w') as f: f.write(output) f.write('\n') else: print(output) except Exception as e: print(f"Error writing output: {e}", file=sys.stderr) sys.exit(1) if __name__ == '__main__': main()