Skip to content

Instantly share code, notes, and snippets.

@stuartcarnie
Last active December 17, 2015 17:39
Show Gist options
  • Save stuartcarnie/5647908 to your computer and use it in GitHub Desktop.
Save stuartcarnie/5647908 to your computer and use it in GitHub Desktop.
Script to pretty json input
#!/usr/bin/env python
r"""Command-line tool to validate and pretty-print JSON
Usage::
$ echo '{"json":"obj"}' | python -m json.tool
{
"json": "obj"
}
$ echo '{ 1.2:3.4}' | python -m json.tool
Expecting property name: line 1 column 2 (char 2)
On OS X, to reformat json on your pasteboard:
pbpaste | json-pretty | pbcopy
"""
import sys
import json
import collections
def main():
if len(sys.argv) == 1:
infile = sys.stdin
outfile = sys.stdout
elif len(sys.argv) == 2:
arg = sys.argv[1]
if (arg in ['--help', '-h']):
print __doc__
sys.exit(0)
infile = open(sys.argv[1], 'rb')
outfile = sys.stdout
elif len(sys.argv) == 3:
infile = open(sys.argv[1], 'rb')
outfile = open(sys.argv[2], 'wb')
else:
raise SystemExit(sys.argv[0] + " [infile [outfile]]")
try:
obj = json.load(infile, object_pairs_hook=collections.OrderedDict)
except ValueError, e:
raise SystemExit(e)
json.dump(obj, outfile, indent=2)
outfile.write('\n')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment