Skip to content

Instantly share code, notes, and snippets.

@doekman
Last active October 5, 2020 18:29
Show Gist options
  • Save doekman/e6e942d03f9dee3e98c080b7a47cd04b to your computer and use it in GitHub Desktop.
Save doekman/e6e942d03f9dee3e98c080b7a47cd04b to your computer and use it in GitHub Desktop.
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