16
16
import sys
17
17
18
18
19
+ def parse_indent (indent ):
20
+ """Parse the argparse indent argument."""
21
+ if indent == 'None' :
22
+ return None
23
+ if indent == r'\t' :
24
+ return '\t '
25
+ try :
26
+ return int (indent )
27
+ except ValueError :
28
+ return indent
29
+
30
+
19
31
def main ():
20
32
prog = 'python -m json.tool'
21
33
description = ('A simple command line interface for json module '
@@ -25,24 +37,33 @@ def main():
25
37
help = 'a JSON file to be validated or pretty-printed' )
26
38
parser .add_argument ('outfile' , nargs = '?' , type = argparse .FileType ('w' ),
27
39
help = 'write the output of infile to outfile' )
40
+ parser .add_argument ('--indent' , default = '4' , type = parse_indent ,
41
+ help = 'Indent level or str for pretty-printing. '
42
+ 'Use None for the most compact representation. '
43
+ r'Use "\t" for tab indentation.' )
28
44
parser .add_argument ('--sort-keys' , action = 'store_true' , default = False ,
29
45
help = 'sort the output of dictionaries alphabetically by key' )
30
46
options = parser .parse_args ()
31
47
48
+ # Read input JSON
32
49
infile = options .infile or sys .stdin
33
- outfile = options .outfile or sys .stdout
34
- sort_keys = options .sort_keys
35
50
with infile :
36
51
try :
37
- if sort_keys :
52
+ if options . sort_keys :
38
53
obj = json .load (infile )
39
54
else :
40
55
obj = json .load (infile ,
41
56
object_pairs_hook = collections .OrderedDict )
42
57
except ValueError as e :
43
58
raise SystemExit (e )
59
+
60
+ # Export JSON
61
+ outfile = options .outfile or sys .stdout
44
62
with outfile :
45
- json .dump (obj , outfile , sort_keys = sort_keys , indent = 4 )
63
+ json .dump (obj , outfile ,
64
+ indent = options .indent ,
65
+ sort_keys = options .sort_keys ,
66
+ )
46
67
outfile .write ('\n ' )
47
68
48
69
0 commit comments