File: json2.py
   1 #!/usr/bin/python3
   2 
   3 # The MIT License (MIT)
   4 #
   5 # Copyright © 2025 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 [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 
  37 # handle standard help cmd-line options, quitting right away in that case
  38 if len(argv) > 1 and argv[1] in ('-h', '--h', '-help', '--help'):
  39     print(info.strip())
  40     exit(0)
  41 
  42 
  43 def json2(w, src) -> None:
  44     dump(load(src), w, indent=2, separators=(',', ': '),
  45         allow_nan=False, check_circular=False)
  46     w.write('\n')
  47 
  48 
  49 def seems_url(s: str) -> bool:
  50     protocols = ('https://', 'http://', 'file://', 'ftp://', 'data:')
  51     return any(s.startswith(p) for p in protocols)
  52 
  53 
  54 try:
  55     if len(argv) < 2:
  56         json2(stdout, stdin.buffer)
  57     elif len(argv) == 2:
  58         name = argv[1]
  59         if name == '-':
  60             json2(stdout, stdin.buffer)
  61         elif seems_url(name):
  62             from urllib.request import urlopen
  63             with urlopen(name) as inp:
  64                 json2(stdout, inp)
  65         else:
  66             with open(name, mode='rb') as inp:
  67                 json2(stdout, inp)
  68     else:
  69         raise ValueError('multiple inputs not allowed')
  70 except BrokenPipeError:
  71     # quit quietly, instead of showing a confusing error message
  72     stderr.close()
  73 except KeyboardInterrupt:
  74     exit(2)
  75 except Exception as e:
  76     print(str(e), file=stderr)
  77     exit(1)