File: json2.py 1 #!/usr/bin/python 2 3 # The MIT License (MIT) 4 # 5 # Copyright (c) 2026 pacman64 6 # 7 # Permission is hereby granted, free of charge, to any person obtaining a copy 8 # of this software and associated documentation files (the "Software"), to deal 9 # in the Software without restriction, including without limitation the rights 10 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 # copies of the Software, and to permit persons to whom the Software is 12 # furnished to do so, subject to the following conditions: 13 # 14 # The above copyright notice and this permission notice shall be included in 15 # all copies or substantial portions of the Software. 16 # 17 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 23 # SOFTWARE. 24 25 26 from json import load, dump 27 from sys import argv, exit, stderr, stdin, stdout 28 29 30 info = ''' 31 json2 [options...] [filepath/URI...] 32 33 JSON-2 reformats valid JSON input into indented multi-line JSON output, 34 using 2 spaces for each indentation level. 35 36 All (optional) leading options start with either single or double-dash: 37 38 -h, -help show this help message 39 ''' 40 41 # handle standard help cmd-line options, quitting right away in that case 42 if len(argv) > 1 and argv[1] in ('-h', '--h', '-help', '--help'): 43 print(info.strip()) 44 exit(0) 45 46 47 def json2(w, src): 48 dump(load(src), w, indent=2, separators=(',', ': '), 49 allow_nan=False, check_circular=False) 50 w.write('\n') 51 52 53 def seems_url(s): 54 protocols = ('https://', 'http://', 'file://', 'ftp://', 'data:') 55 return any(s.startswith(p) for p in protocols) 56 57 58 args = argv[1:] 59 60 if len(args) > 0: 61 s = args[0] 62 if s != '-' and s != '--' and s.startswith('-'): 63 print(f'json2: unsupported option {s}') 64 exit(1) 65 66 if len(args) > 0 and args[0] == '--': 67 args = args[1:] 68 69 try: 70 if len(args) > 1: 71 raise ValueError('json2: multiple inputs not allowed') 72 name = args[0] if len(args) > 0 else '-' 73 74 if name == '-': 75 json2(stdout, stdin.buffer) 76 elif seems_url(name): 77 from urllib.request import urlopen 78 with urlopen(name) as inp: 79 json2(stdout, inp) 80 else: 81 with open(name, mode='rb') as inp: 82 json2(stdout, inp) 83 except BrokenPipeError: 84 # quit quietly, instead of showing a confusing error message 85 stderr.close() 86 except KeyboardInterrupt: 87 exit(2) 88 except Exception as e: 89 print(str(e), file=stderr) 90 exit(1)