-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathprettyjson
executable file
·49 lines (37 loc) · 1.28 KB
/
prettyjson
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/usr/bin/env python3
__license__ = 'GPLv3'
__author__ = 'haxwithaxe'
__copyright__ = 'Copyright (c) 2016 haxwithaxe'
import argparse
import json
import sys
def load(filename):
if filename is None:
json_dict = json.load(sys.stdin)
else:
with open(filename, 'r') as json_file:
json_dict = json.load(json_file)
return json_dict
def format_json(json_dict, output_filename, to_stdout):
if output_filename:
with open(output_filename, 'w') as output_file:
json.dump(json_dict, output_file, sort_keys=True, indent=4)
if to_stdout:
print(json.dumps(json_dict, sort_keys=True, indent=4))
def handle_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('--print', '-p', default=False, action='store_true')
parser.add_argument('--output', '-o', default=None, help='''Output filename. Use "-" for stdout.''')
parser.add_argument('filename', nargs='?', help='''Input filename. Use "-" for stdin.''')
args = parser.parse_args()
to_stdout = args.print
if args.output in (None, '-'):
to_stdout = True
output_filename = None
else:
output_filename = args.output
input_filename = None if args.filename in (None, '-') else args.filename
json_dict = load(input_filename)
format_json(json_dict, output_filename, to_stdout)
if __name__ == '__main__':
handle_arguments()