Skip to content

Instantly share code, notes, and snippets.

@fcicq
Created June 30, 2012 03:30
Show Gist options
  • Save fcicq/3022040 to your computer and use it in GitHub Desktop.
Save fcicq/3022040 to your computer and use it in GitHub Desktop.
Python JSON Prettifier by Sujit Pal, from http://sujitpal.blogspot.com/2011/05/python-json-prettifier.html
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Converts the specified JSON file with the specified encoding
# (default encoding is utf8 if not specified) into a formatted
# version with the specified indent (2 if not specified) and
# writes to STDOUT.
#
# Usage: jsoncat.py inputfile.json [input_encoding] [indent]
#
import sys
import json
import codecs
def usage():
print "Usage: %s input.json [input_encoding] [indent]" % sys.argv[0]
print "input.json - the input file to read"
print "input_encoding - optional, default utf-8"
print "indent - optional, default 2"
sys.exit(-1)
def prettyPrint(obj, indent, depth, suffix=False):
if isinstance(obj, list):
sys.stdout.write("%s[\n" % str(" " * indent * depth))
sz = len(obj)
i = 1
for row in obj:
prettyPrint(row, indent, depth + 1, i < sz)
i = i + 1
ct = "," if suffix else ""
sys.stdout.write("%s]%s\n" % (str(" " * indent * depth), ct))
elif isinstance(obj, dict):
sys.stdout.write("%s{\n" % str(" " * indent * depth))
sz = len(obj.keys())
i = 1
for key in obj.keys():
sys.stdout.write("%s%s :" % (str(" " * indent * (depth + 1)), qq(key)))
val = obj[key]
if isinstance(val, list) or isinstance(val, dict):
prettyPrint(val, indent, depth + 1, i < sz)
else:
prettyPrint(val, 1, 1, i < sz)
i = i + 1
ct = "," if suffix else ""
sys.stdout.write("%s}%s\n" % (str(" " * indent * depth), ct))
else:
ct = "," if suffix else ""
sys.stdout.write("%s%s%s\n" % (str(" " * indent * depth), qq(obj), ct))
def qq(obj):
if isinstance(obj, unicode):
return "\"" + obj.encode('ascii', 'xmlcharrefreplace') + "\""
else:
return repr(obj)
def main():
if len(sys.argv) < 2 and len(sys.argv) > 4:
usage()
encoding = "utf-8" if len(sys.argv) == 2 else sys.argv[2]
indent = 2 if len(sys.argv) == 3 else sys.argv[3]
infile = codecs.open(sys.argv[1], "r", encoding)
content = infile.read()
infile.close()
jsobj = json.loads(content)
prettyPrint(jsobj, indent, 0)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment