File: minizj.py
   1 #!/usr/bin/python3
   2 
   3 # The MIT License (MIT)
   4 #
   5 # Copyright © 2020-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 info = '''
  27 minizj [keys...]
  28 
  29 This is the MINImal version of the Zoom Json tool.
  30 '''
  31 
  32 
  33 from json import dump, load
  34 from sys import argv, exit, stderr, stdin, stdout
  35 
  36 
  37 def match_key(kv, key):
  38     if key in kv:
  39         return key
  40 
  41     low = key.lower()
  42     for k in kv.keys():
  43         if low == k.lower():
  44             return k
  45 
  46     try:
  47         i = int(key)
  48         l = len(kv)
  49         if i < 0:
  50             i += l
  51 
  52         if not (-l <= i < l):
  53             return key
  54 
  55         for j, k in enumerate(kv.keys()):
  56             if i == j:
  57                 return k
  58     except Exception:
  59         return key
  60 
  61     return key
  62 
  63 
  64 def typeof(x):
  65     # return str(type(x))
  66     return {
  67         type(None): 'null',
  68         bool: 'boolean',
  69         dict: 'object',
  70         float: 'number',
  71         int: 'number',
  72         str: 'string',
  73         list: 'array',
  74         tuple: 'array',
  75     }.get(type(x), 'other')
  76 
  77 
  78 def zoom(data, keys):
  79     for i, k in enumerate(keys):
  80         if isinstance(data, dict):
  81             # m = match_key(data, k)
  82             # if not (m in data):
  83             #     raise Exception(f'{m}: object doesn\'t have that key')
  84             data = data.get(match_key(data, k), None)
  85             continue
  86 
  87         if isinstance(data, (list, tuple)):
  88             if k == '+':
  89                 pick = keys[i + 1:]
  90                 return [{k: e.get(k, None) for k in pick}
  91                         for e in data if isinstance(e, dict)]
  92             if k == '-':
  93                 avoid = set(keys[i + 1:])
  94                 return [{k: v for (k, v) in e.items() if not (k in avoid)}
  95                         for e in data if isinstance(e, dict)]
  96             if k == '.':
  97                 rest = keys[i + 1:]
  98                 return [zoom(e, rest) for e in data]
  99 
 100             try:
 101                 k = int(k)
 102                 l = len(data)
 103                 data = data[k] if -l <= k < l else None
 104             except Exception:
 105                 # raise Exception(f'{k}: arrays don\'t have keys like objects')
 106                 data = None
 107             continue
 108 
 109         # return None
 110         # data = None
 111         raise Exception(f'{k}: can\'t zoom on value of type {typeof(data)}')
 112 
 113     return data
 114 
 115 
 116 try:
 117     data = load(stdin)
 118     data = zoom(data, argv[1:])
 119     # dump(data, stdout, indent=None, separators=(',', ':'), allow_nan=False)
 120     dump(data, stdout, indent=2, separators=(',', ': '), allow_nan=False)
 121     print()
 122 except BrokenPipeError:
 123     exit(0)
 124 except Exception as e:
 125     print(f'\x1b[31m{str(e)}\x1b[0m', file=stderr)
 126     exit(1)