File: minizj.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 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 {
  66         type(None): 'null',
  67         bool: 'boolean',
  68         dict: 'object',
  69         float: 'number',
  70         int: 'number',
  71         str: 'string',
  72         list: 'array',
  73         tuple: 'array',
  74     }.get(type(x), 'other')
  75 
  76 
  77 def zoom(data, keys):
  78     for i, k in enumerate(keys):
  79         if isinstance(data, dict):
  80             # m = match_key(data, k)
  81             # if not (m in data):
  82             #     raise Exception(f'{m}: object doesn\'t have that key')
  83             data = data.get(match_key(data, k), None)
  84             continue
  85 
  86         if isinstance(data, (list, tuple)):
  87             if k == '+':
  88                 pick = keys[i + 1:]
  89                 return [{k: e.get(k, None) for k in pick}
  90                         for e in data if isinstance(e, dict)]
  91             if k == '-':
  92                 avoid = set(keys[i + 1:])
  93                 return [{k: v for (k, v) in e.items() if not (k in avoid)}
  94                         for e in data if isinstance(e, dict)]
  95             if k == '.':
  96                 rest = keys[i + 1:]
  97                 return [zoom(e, rest) for e in data]
  98 
  99             try:
 100                 k = int(k)
 101                 l = len(data)
 102                 data = data[k] if -l <= k < l else None
 103             except Exception:
 104                 # raise Exception(f'{k}: arrays don\'t have keys like objects')
 105                 data = None
 106             continue
 107 
 108         # return None
 109         # data = None
 110         raise Exception(f'{k}: can\'t zoom on value of type {typeof(data)}')
 111 
 112     return data
 113 
 114 
 115 try:
 116     data = load(stdin)
 117     data = zoom(data, argv[1:])
 118     dump(data, stdout, indent=2, separators=(',', ': '), allow_nan=False)
 119     print()
 120 except BrokenPipeError:
 121     exit(0)
 122 except Exception as e:
 123     print(str(e), file=stderr)
 124     exit(1)