#!/usr/bin/python3 # The MIT License (MIT) # # Copyright © 2020-2025 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 = ''' minitj [options...] [python expression] [file/URI...] This is the MINImal version of the Transform Json tool: just use a Python expression using any of the variables `v`, `value`, `d`, or `data` to act on the decoded JSON input. The result is emitted as JSON output. ''' from json import dump, load from sys import argv, exit, stderr, stdin, stdout from typing import Iterable if len(argv) < 2: print(info.strip(), file=stderr) exit(0) if len(argv) == 2 and argv[1] in ('-h', '--h', '-help', '--help'): print(info.strip()) exit(0) class Skip: pass skip = Skip() def rescue(attempt, fallback = None): try: return attempt() except Exception as e: if callable(fallback): return fallback(e) return fallback catch = rescue catched = rescue caught = rescue recover = rescue recovered = rescue rescued = rescue def result_needs_fixing(x): if x is None or isinstance(x, (bool, int, float, str)): return False rec = result_needs_fixing if isinstance(x, dict): return any(rec(k) or rec(v) for k, v in x.items()) if isinstance(x, (list, tuple)): return any(rec(e) for e in x) return True def fix_result(x, default): if x is type: return type(default).__name__ # if expression results in a func, auto-call it with the original data if callable(x): x = x(default) if x is None or isinstance(x, (bool, int, float, str)): return x rec = fix_result if isinstance(x, dict): return { rec(k, default): rec(v, default) for k, v in x.items() if not (isinstance(k, Skip) or isinstance(v, Skip)) } if isinstance(x, Iterable): return tuple(rec(e, default) for e in x if not isinstance(e, Skip)) if isinstance(x, Exception): raise x return None if isinstance(x, Skip) else str(x) def seems_url(path): protocols = ('https://', 'http://', 'file://', 'ftp://', 'data:') return any(path.startswith(p) for p in protocols) cr = '\r' crlf = '\r\n' dquo = '"' dquote = '"' empty = '' lcurly = '{' lf = '\n' rcurly = '}' s = '' squo = '\'' squote = '\'' utf8bom = '\xef\xbb\xbf' nil = None none = None null = None no_input_opts = ( '=', '-n', '--n', '-nil', '--nil', '-none', '--none', '-null', '--null', ) compact_output_opts = ( '-c', '--c', '-compact', '--compact', '-j0', '--j0', '-json0', '--json0', ) more_modules_opts = ('-mm', '--mm', '-more', '--more') args = argv[1:] no_input = False compact_output = False while len(args) > 0: if args[0] in no_input_opts: no_input = True args = args[1:] continue if args[0] in compact_output_opts: compact_output = True args = args[1:] continue if args[0] in more_modules_opts: import functools import itertools import math import random import statistics import string import time args = args[1:] continue break try: expr = 'data' if len(args) > 0: expr = args[0] args = args[1:] if expr == '.': expr = 'data' if len(args) > 1: raise Exception('can\'t use more than 1 input') path = '-' if len(args) == 0 else args[0] if no_input: data = None elif path == '-': data = load(stdin) elif seems_url(path): from io import TextIOWrapper from urllib.request import urlopen with urlopen(path) as inp: with TextIOWrapper(inp, encoding='utf-8') as txt: data = load(txt) else: with open(path, encoding='utf-8') as inp: data = load(inp) exec = None open = None v = val = value = d = dat = data v = eval(expr) if result_needs_fixing(v): v = fix_result(v, data) if compact_output: dump(v, stdout, indent=None, separators=(',', ':'), allow_nan=False) else: dump(v, stdout, indent=2, separators=(',', ': '), allow_nan=False) print() except BrokenPipeError: # quit quietly, instead of showing a confusing error message stderr.close() exit(0) except KeyboardInterrupt: exit(2) except Exception as e: print(f'\x1b[31m{str(e)}\x1b[0m', file=stderr) exit(1)