File: minitj.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 minitj [options...] [python expression] [file/URI...]
  28 
  29 This is the MINImal version of the Transform Json tool: just use a Python
  30 expression using any of the variables `v`, `value`, `d`, or `data` to act
  31 on the decoded JSON input. The result is emitted as JSON output.
  32 '''
  33 
  34 
  35 from json import dump, load
  36 from sys import argv, exit, stderr, stdin, stdout
  37 from typing import Iterable
  38 
  39 
  40 if len(argv) < 2:
  41     print(info.strip(), file=stderr)
  42     exit(1)
  43 if len(argv) > 1 and argv[1] in ('-h', '--h', '-help', '--help'):
  44     print(info.strip())
  45     exit(0)
  46 
  47 
  48 class Skip:
  49     pass
  50 
  51 
  52 skip = Skip()
  53 
  54 
  55 def rescue(attempt, fallback = None):
  56     try:
  57         return attempt()
  58     except Exception as e:
  59         if callable(fallback):
  60             return fallback(e)
  61         return fallback
  62 
  63 catch = rescue
  64 catched = rescue
  65 caught = rescue
  66 recover = rescue
  67 recovered = rescue
  68 rescued = rescue
  69 
  70 
  71 def result_needs_fixing(x):
  72     if x is None or isinstance(x, (bool, int, float, str)):
  73         return False
  74     rec = result_needs_fixing
  75     if isinstance(x, dict):
  76         return any(rec(k) or rec(v) for k, v in x.items())
  77     if isinstance(x, (list, tuple)):
  78         return any(rec(e) for e in x)
  79     return True
  80 
  81 
  82 def fix_result(x, default):
  83     if x is type:
  84         return type(default).__name__
  85 
  86     # if expression results in a func, auto-call it with the original data
  87     if callable(x):
  88         x = x(default)
  89 
  90     if x is None or isinstance(x, (bool, int, float, str)):
  91         return x
  92 
  93     rec = fix_result
  94 
  95     if isinstance(x, dict):
  96         return {
  97             rec(k, default): rec(v, default) for k, v in x.items() if not
  98                 (isinstance(k, Skip) or isinstance(v, Skip))
  99         }
 100     if isinstance(x, Iterable):
 101         return tuple(rec(e, default) for e in x if not isinstance(e, Skip))
 102 
 103     if isinstance(x, Exception):
 104         raise x
 105 
 106     return None if isinstance(x, Skip) else str(x)
 107 
 108 
 109 def seems_url(path):
 110     protocols = ('https://', 'http://', 'file://', 'ftp://', 'data:')
 111     return any(path.startswith(p) for p in protocols)
 112 
 113 
 114 dquo = '"'
 115 dquote = '"'
 116 lcurly = '{'
 117 rcurly = '}'
 118 squo = '\''
 119 squote = '\''
 120 utf8bom = '\xef\xbb\xbf'
 121 
 122 nil = None
 123 none = None
 124 null = None
 125 
 126 
 127 no_input_opts = (
 128     '=', '-n', '--n', '-nil', '--nil', '-none', '--none', '-null', '--null',
 129 )
 130 compact_output_opts = (
 131     '-c', '--c', '-compact', '--compact', '-j0', '--j0', '-json0', '--json0',
 132 )
 133 more_modules_opts = ('-mm', '--mm', '-more', '--more')
 134 
 135 args = argv[1:]
 136 no_input = False
 137 compact_output = False
 138 
 139 while len(args) > 0:
 140     if args[0] in no_input_opts:
 141         no_input = True
 142         args = args[1:]
 143         continue
 144 
 145     if args[0] in compact_output_opts:
 146         compact_output = True
 147         args = args[1:]
 148         continue
 149 
 150     if args[0] in more_modules_opts:
 151         import functools
 152         import itertools
 153         import math
 154         import random
 155         import statistics
 156         import string
 157         import time
 158         args = args[1:]
 159         continue
 160 
 161     break
 162 
 163 
 164 try:
 165     expr = 'data'
 166     if len(args) > 0:
 167         expr = args[0]
 168         args = args[1:]
 169 
 170     if expr == '.':
 171         expr = 'data'
 172 
 173     if len(args) > 1:
 174         raise Exception('can\'t use more than 1 input')
 175     path = '-' if len(args) == 0 else args[0]
 176 
 177     if no_input:
 178         data = None
 179     elif path == '-':
 180         data = load(stdin)
 181     elif seems_url(path):
 182         from io import TextIOWrapper
 183         from urllib.request import urlopen
 184         with urlopen(path) as inp:
 185             with TextIOWrapper(inp, encoding='utf-8') as txt:
 186                 data = load(txt)
 187     else:
 188         with open(path, encoding='utf-8') as inp:
 189             data = load(inp)
 190 
 191     exec = None
 192     open = None
 193     v = val = value = d = dat = data
 194     v = eval(expr)
 195     if result_needs_fixing(v):
 196         v = fix_result(v, data)
 197 
 198     if compact_output:
 199         dump(v, stdout, indent=None, separators=(',', ':'), allow_nan=False)
 200     else:
 201         dump(v, stdout, indent=2, separators=(',', ': '), allow_nan=False)
 202     print()
 203 except BrokenPipeError:
 204     # quit quietly, instead of showing a confusing error message
 205     stderr.close()
 206     exit(0)
 207 except KeyboardInterrupt:
 208     exit(2)
 209 except Exception as e:
 210     print(f'\x1b[31m{str(e)}\x1b[0m', file=stderr)
 211     exit(1)