File: zj.py
   1 #!/usr/bin/python3
   2 
   3 # The MIT License (MIT)
   4 #
   5 # Copyright © 2024 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 # zj [keys/indices...]
  27 #
  28 # Zoom Json digs into a subset of valid JSON input, using the given mix of
  29 # keys and array-indices, either 0-based or negative.
  30 
  31 
  32 from json import load, dump
  33 from sys import argv, exit, stderr, stdin, stdout
  34 from typing import Any, List
  35 
  36 
  37 # info is the help message shown when asked to
  38 info = '''
  39 zj [keys/indices...]
  40 
  41 Zoom Json digs into a subset of valid JSON input, using the given mix of
  42 keys and array-indices, either 0-based or negative.
  43 '''.strip()
  44 
  45 # handle standard help cmd-line options, quitting right away in that case
  46 if len(argv) == 2 and argv[1] in ('-h', '--h', '-help', '--help'):
  47     print(info, file=stderr)
  48     exit(0)
  49 
  50 
  51 def zoom(data: Any, keys: List[str]) -> Any:
  52     '''Dig into the value given, using the keys given.'''
  53 
  54     for k in keys:
  55         if isinstance(data, dict):
  56             data = data[k]
  57             continue
  58 
  59         if isinstance(data, list):
  60             try:
  61                 i = int(k)
  62             except:
  63                 raise Exception(f'can\'t index an array with {k}')
  64             data = data[i]
  65             continue
  66 
  67         raise ValueError(f'current top-level value isn\'t indexable')
  68 
  69     return data
  70 
  71 
  72 try:
  73     stdout.reconfigure(newline='\n', encoding='utf-8')
  74     data = zoom(load(stdin.buffer), argv[1:])
  75     dump(data, stdout, indent=2, allow_nan=False, separators=(', ', ': '))
  76     stdout.write('\n')
  77 except (BrokenPipeError, KeyboardInterrupt):
  78     # quit quietly, instead of showing a confusing error message
  79     stderr.flush()
  80     stderr.close()
  81 except Exception as e:
  82     print(f'\x1b[31m{e}\x1b[0m', file=stderr)
  83     exit(1)