Created
June 4, 2026 20:43
-
-
Save obormot/a2b92e7485a74fac1778268379f2d090 to your computer and use it in GitHub Desktop.
Pretty print python dict or JSON from stdin, with optional value masking
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # pipe to jq for colored output | |
| pyjq(){ "${HOME}/pyjq" "$@" | jq . ;} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| """ | |
| pretty print python dict or JSON from stdin | |
| """ | |
| import argparse | |
| import json | |
| import sys | |
| parser = argparse.ArgumentParser(description='Pretty-print a python dict or JSON from stdin') | |
| parser.add_argument('--mask', action='store_true', help='anonymize string values (keep first 4 chars, then ****)') | |
| parser.add_argument('--mask-keep', default='', metavar='FIELDS', help='comma-separated field names to leave unmasked (only with --mask)') | |
| args = parser.parse_args() | |
| keep = set(f.strip() for f in args.mask_keep.split(',') if f.strip()) | |
| def mask(value, key=None): | |
| if isinstance(value, str): | |
| if key in keep: | |
| return value | |
| return value[:4] + '****' if len(value) > 4 else value | |
| if isinstance(value, dict): | |
| return {k: mask(v, key=k) for k, v in value.items()} | |
| if isinstance(value, list): | |
| return [mask(v, key=key) for v in value] | |
| return value | |
| inp = sys.stdin.read() | |
| try: | |
| dd = eval(inp) | |
| except: | |
| sys.exit('Error: expecting a python dict or JSON as input') | |
| if args.mask: | |
| dd = mask(dd) | |
| print(json.dumps(dd, indent=4)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment