#!/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 = ''' minitj [options...] [python expression] [files/URIs...] This is the MINImal version of the Transform Json tool. ''' from io import TextIOWrapper from json import dump, load from sys import argv, exit, stderr, stdin, stdout from typing import Iterable if len(argv) < 2 or argv[1] in ('-h', '--h', '-help', '--help'): print(info.strip(), file=stderr) exit(0) class Skip: pass skip = Skip() def recover(attempt, fallback = None): try: return attempt() except Exception as e: if callable(fallback): return fallback(e) return fallback recovered = recover rescue = recover rescued = recover 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) crlf = '\r\n' dquo = '"' dquote = '"' empty = '' lcurly = '{' lf = '\n' rcurly = '}' s = '' squo = '\'' squote = '\'' nil = None none = None null = None args = argv[1:] if any(seems_url(e) for e in args): from urllib.request import urlopen no_input_opts = ( '=', '-n', '--n', '-nil', '--nil', '-none', '--none', '-null', '--null', ) compact_output_opts = ( '-c', '--c', '-compact', '--compact', '-j0', '--j0', '-json0', '--json0', ) 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 break import functools import itertools import math import random import statistics import string import time 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 named input') path = '-' if len(args) == 0 else args[0] if no_input: data = None elif path == '-': data = load(stdin) elif seems_url(path): 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) v = value = d = data exec = None open = None 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: exit(0) except Exception as e: print(f'\x1b[31m{str(e)}\x1b[0m', file=stderr) exit(1)