blob: 5dee0a744b2a99e1e88c52dfecfec56a8598d10f [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
Christian Heimes90540002008-05-08 14:29:10 +000014import json
Benjamin Peterson940e2072014-03-21 23:17:29 -050015import sys
16
Christian Heimes90540002008-05-08 14:29:10 +000017
18def main():
Benjamin Peterson940e2072014-03-21 23:17:29 -050019 prog = 'python -m json.tool'
20 description = ('A simple command line interface for json module '
21 'to validate and pretty-print JSON objects.')
22 parser = argparse.ArgumentParser(prog=prog, description=description)
Inada Naoki808769f2019-12-04 18:39:31 +090023 parser.add_argument('infile', nargs='?',
24 type=argparse.FileType(encoding="utf-8"),
Hervé Beraud4d45a3b2019-05-14 18:52:42 +020025 help='a JSON file to be validated or pretty-printed',
26 default=sys.stdin)
Inada Naoki808769f2019-12-04 18:39:31 +090027 parser.add_argument('outfile', nargs='?',
28 type=argparse.FileType('w', encoding="utf-8"),
Hervé Beraud4d45a3b2019-05-14 18:52:42 +020029 help='write the output of infile to outfile',
30 default=sys.stdout)
Berker Peksag39e4c4d2014-11-10 09:56:54 +020031 parser.add_argument('--sort-keys', action='store_true', default=False,
32 help='sort the output of dictionaries alphabetically by key')
wim glennefefe252019-12-06 00:44:01 -060033 parser.add_argument('--no-ensure-ascii', dest='ensure_ascii', action='store_false',
34 help='disable escaping of non-ASCII characters')
HongWeipengf1944792018-11-07 18:09:32 +080035 parser.add_argument('--json-lines', action='store_true', default=False,
Daniel Himmelstein15fb7fa2019-12-07 07:14:40 -070036 help='parse input using the JSON Lines format. '
37 'Use with --no-indent or --compact to produce valid JSON Lines output.')
Daniel Himmelstein03257942019-12-04 01:15:19 -050038 group = parser.add_mutually_exclusive_group()
39 group.add_argument('--indent', default=4, type=int,
40 help='separate items with newlines and use this number '
41 'of spaces for indentation')
42 group.add_argument('--tab', action='store_const', dest='indent',
43 const='\t', help='separate items with newlines and use '
44 'tabs for indentation')
45 group.add_argument('--no-indent', action='store_const', dest='indent',
46 const=None,
47 help='separate items with spaces rather than newlines')
48 group.add_argument('--compact', action='store_true',
49 help='suppress all whitespace separation (most compact)')
Benjamin Peterson940e2072014-03-21 23:17:29 -050050 options = parser.parse_args()
51
Daniel Himmelstein03257942019-12-04 01:15:19 -050052 dump_args = {
53 'sort_keys': options.sort_keys,
54 'indent': options.indent,
wim glennefefe252019-12-06 00:44:01 -060055 'ensure_ascii': options.ensure_ascii,
Daniel Himmelstein03257942019-12-04 01:15:19 -050056 }
57 if options.compact:
58 dump_args['indent'] = None
59 dump_args['separators'] = ',', ':'
60
61 with options.infile as infile, options.outfile as outfile:
Ezio Melotti057bcb42012-11-29 02:15:18 +020062 try:
Daniel Himmelstein03257942019-12-04 01:15:19 -050063 if options.json_lines:
HongWeipengf1944792018-11-07 18:09:32 +080064 objs = (json.loads(line) for line in infile)
65 else:
66 objs = (json.load(infile), )
67 for obj in objs:
Daniel Himmelstein03257942019-12-04 01:15:19 -050068 json.dump(obj, outfile, **dump_args)
HongWeipengf1944792018-11-07 18:09:32 +080069 outfile.write('\n')
Ezio Melotti057bcb42012-11-29 02:15:18 +020070 except ValueError as e:
71 raise SystemExit(e)
Christian Heimes90540002008-05-08 14:29:10 +000072
73
74if __name__ == '__main__':
Dong-hee Na700cb582020-03-10 16:41:44 +090075 try:
76 main()
77 except BrokenPipeError as exc:
78 sys.exit(exc.errno)