@@ -22,27 +22,24 @@ def main():
22
22
'to validate and pretty-print JSON objects.' )
23
23
parser = argparse .ArgumentParser (prog = prog , description = description )
24
24
parser .add_argument ('infile' , nargs = '?' , type = argparse .FileType (),
25
+ default = sys .stdin ,
25
26
help = 'a JSON file to be validated or pretty-printed' )
26
27
parser .add_argument ('outfile' , nargs = '?' , type = argparse .FileType ('w' ),
28
+ default = sys .stdout ,
27
29
help = 'write the output of infile to outfile' )
28
- parser .add_argument ('--sort-keys' , action = 'store_true' , default = False ,
29
- help = 'sort the output of dictionaries alphabetically by key' )
30
+ parser .add_argument ('--sort-keys' , action = 'store_true' ,
31
+ help = 'sort the output of dictionaries by key' )
30
32
options = parser .parse_args ()
31
33
32
- infile = options .infile or sys .stdin
33
- outfile = options .outfile or sys .stdout
34
- sort_keys = options .sort_keys
35
- with infile :
34
+ hook = collections .OrderedDict if options .sort_keys else None
35
+ with options .infile as infile :
36
36
try :
37
- if sort_keys :
38
- obj = json .load (infile )
39
- else :
40
- obj = json .load (infile ,
41
- object_pairs_hook = collections .OrderedDict )
37
+ obj = json .load (infile , object_pairs_hook = hook )
42
38
except ValueError as e :
43
39
raise SystemExit (e )
44
- with outfile :
45
- json .dump (obj , outfile , sort_keys = sort_keys , indent = 4 )
40
+
41
+ with options .outfile as outfile :
42
+ json .dump (obj , outfile , sort_keys = options .sort_keys , indent = 4 )
46
43
outfile .write ('\n ' )
47
44
48
45
0 commit comments