Pretty Print JSON with a Twist
#!/usr/bin/env python3 | |
# See blog article: | |
# https://blog.zanstra.com/2020/10/05/Pretty-printing-JSON-with-a-twist.html | |
import json, re, sys | |
def json_stringify(obj, indent=2): | |
if not isinstance(indent, str): | |
indent = ' ' * indent | |
result = json.dumps(obj, indent=indent) | |
r_indent=re.escape(indent) | |
if indent[:1]=='\t': | |
r_indent0 = '' | |
r_indent1N = re.escape(indent) | |
else: | |
r_indent0 = re.escape(indent[:1]) | |
r_indent1N = re.escape(indent[1:]) | |
rx_indent = r'([,{[]) *\n((?:%s)*)%s(%s)' % (r_indent, r_indent0, r_indent1N) | |
result = re.sub(rx_indent, r'\n\2\1\3', result) | |
return result[1:] if result[:1]=='\n' else result | |
obj = json.load(sys.stdin) | |
print(json_stringify(obj)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment