blob: 4f3182c0c1e7f11396e252f435fd6e63c4975a0d [file] [log] [blame]
Christian Heimes90540002008-05-08 14:29:10 +00001r"""Command-line tool to validate and pretty-print JSON
2
3Usage::
4
Benjamin Petersonc6b607d2009-05-02 12:36:44 +00005 $ echo '{"json":"obj"}' | python -m json.tool
Christian Heimes90540002008-05-08 14:29:10 +00006 {
7 "json": "obj"
8 }
Benjamin Petersonc6b607d2009-05-02 12:36:44 +00009 $ echo '{ 1.2:3.4}' | python -m json.tool
Serhiy Storchakac510a042013-02-21 20:19:16 +020010 Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
Christian Heimes90540002008-05-08 14:29:10 +000011
12"""
Benjamin Peterson940e2072014-03-21 23:17:29 -050013import argparse
Berker Peksag39e4c4d2014-11-10 09:56:54 +020014import collections
Christian Heimes90540002008-05-08 14:29:10 +000015import json
Benjamin Peterson940e2072014-03-21 23:17:29 -050016import sys
17
Christian Heimes90540002008-05-08 14:29:10 +000018
19def main():
Benjamin Peterson940e2072014-03-21 23:17:29 -050020 prog = 'python -m json.tool'
21 description = ('A simple command line interface for json module '
22 'to validate and pretty-print JSON objects.')
23 parser = argparse.ArgumentParser(prog=prog, description=description)
24 parser.add_argument('infile', nargs='?', type=argparse.FileType(),
25 help='a JSON file to be validated or pretty-printed')
26 parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
27 help='write the output of infile to outfile')
Berker Peksag39e4c4d2014-11-10 09:56:54 +020028 parser.add_argument('--sort-keys', action='store_true', default=False,
29 help='sort the output of dictionaries alphabetically by key')
Benjamin Peterson940e2072014-03-21 23:17:29 -050030 options = parser.parse_args()
31
32 infile = options.infile or sys.stdin
33 outfile = options.outfile or sys.stdout
Berker Peksag39e4c4d2014-11-10 09:56:54 +020034 sort_keys = options.sort_keys
Ezio Melotti057bcb42012-11-29 02:15:18 +020035 with infile:
36 try:
Berker Peksag39e4c4d2014-11-10 09:56:54 +020037 if sort_keys:
38 obj = json.load(infile)
39 else:
40 obj = json.load(infile,
41 object_pairs_hook=collections.OrderedDict)
Ezio Melotti057bcb42012-11-29 02:15:18 +020042 except ValueError as e:
43 raise SystemExit(e)
44 with outfile:
Berker Peksag39e4c4d2014-11-10 09:56:54 +020045 json.dump(obj, outfile, sort_keys=sort_keys, indent=4)
Ezio Melotti057bcb42012-11-29 02:15:18 +020046 outfile.write('\n')
Christian Heimes90540002008-05-08 14:29:10 +000047
48
49if __name__ == '__main__':
50 main()