Skip to content

Instantly share code, notes, and snippets.

Last active October 5, 2020 18:29
What would you like to do?
Pretty Print JSON with a Twist
#!/usr/bin/env python3
# See blog article:
import json, re, sys
def json_stringify(obj, indent=2):
if not isinstance(indent, str):
indent = ' ' * indent
result = json.dumps(obj, indent=indent)
if indent[:1]=='\t':
r_indent0 = ''
r_indent1N = re.escape(indent)
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment