Last active
February 28, 2017 20:15
-
-
Save arlago/9e91b19bc14d87a108a2 to your computer and use it in GitHub Desktop.
Python terminal json pretty print
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import json | |
import sys | |
import argparse | |
from collections import OrderedDict | |
parser = argparse.ArgumentParser(description='JSON pretty print') | |
parser.add_argument('-i', type=int, default=2, help='Number of spaces of identation.') | |
parser.add_argument('-f', help='Reads JSON from a file.') | |
parser.add_argument('-p', action='store_true', help='Pipe input.') | |
parser.add_argument('-s', action='store_true', help='Sort keys of the JSON in alphabetic order.') | |
parser.add_argument('json', nargs=argparse.REMAINDER, help='It must be the last argument.') | |
args = parser.parse_args() | |
if args.json: | |
json_obj = json.loads(args.json[0], object_pairs_hook=OrderedDict) | |
elif args.p: | |
json_obj = json.load(sys.stdin, object_pairs_hook=OrderedDict) | |
elif args.f: | |
with open(args.f, 'r') as content_file: | |
file_content = content_file.read() | |
json_obj = json.loads(file_content, object_pairs_hook=OrderedDict) | |
else: | |
print("Where is the JSON!") | |
exit() | |
print json.dumps(json_obj, sort_keys=args.s, | |
indent=args.i, separators=(',', ': ')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment