#!/usr/bin/python3 # The MIT License (MIT) # # Copyright © 2024 pacman64 # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the “Software”), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. info = ''' minizj [keys...] This is the MINImal version of the Zoom Json tool. ''' from json import dump, load from sys import argv, exit, stderr, stdin, stdout def match_key(kv, key): if key in kv: return key low = key.lower() for k in kv.keys(): if low == k.lower(): return k try: i = int(key) l = len(kv) if i < 0: i += l if not (-l <= i < l): return key for j, k in enumerate(kv.keys()): if i == j: return k except Exception as _: return key return key def typeof(x): # return str(type(x)) return { type(None): 'null', bool: 'boolean', dict: 'object', float: 'number', int: 'number', str: 'string', list: 'array', tuple: 'array', }.get(type(x), 'other') def zoom(data, keys): for k in keys: if isinstance(data, dict): # m = match_key(data, k) # if not (m in data): # raise Exception(f'{m}: object doesn\'t have that key') data = data.get(match_key(data, k), None) continue if isinstance(data, (list, tuple)): try: k = int(k) l = len(data) data = data[k] if -l <= k < l else None except Exception as _: # raise Exception(f'{k}: arrays don\'t have keys like objects') data = None continue # return None # if not (data is None): # data = None # continue raise Exception(f'{k}: can\'t zoom on value of type {typeof(data)}') return data try: data = load(stdin) data = zoom(data, argv[1:]) # dump(data, stdout, indent=None, separators=(',', ':'), allow_nan=False) dump(data, stdout, indent=2, separators=(',', ': '), allow_nan=False) print() except BrokenPipeError: exit(0) except Exception as e: print(f'\x1b[31m{str(e)}\x1b[0m', file=stderr) exit(1)