Debian Codegraph @

Lib/json/tool.py

raw
1 """Command-line tool to validate and pretty-print JSON
2
3 See `json.__main__` for a usage example (invocation as
4 `python -m json.tool` is supported for backwards compatibility).
5 """
6 import argparse
7 import json
8 import re
9 import sys
10 from _colorize import get_theme, can_colorize
11
12
13 # The string we are colorizing is valid JSON,
14 # so we can use a looser but simpler regex to match
15 # the various parts, most notably strings and numbers,
16 # where the regex given by the spec is much more complex.
17 _color_pattern = re.compile(r'''
18 (?P<key>"(\\.|[^"\\])*")(?=:) |
19 (?P<string>"(\\.|[^"\\])*") |
20 (?P<number>NaN|-?Infinity|[0-9\-+.Ee]+) |
21 (?P<boolean>true|false) |
22 (?P<null>null)
23 ''', re.VERBOSE)
24
25 _group_to_theme_color = {
26 "key": "definition",
27 "string": "string",
28 "number": "number",
29 "boolean": "keyword",
30 "null": "keyword",
31 }
32
33
34 def _colorize_json(json_str, theme):
35 def _replace_match_callback(match):
36 for group, color in _group_to_theme_color.items():
37 if m := match.group(group):
38 return f"{theme[color]}{m}{theme.reset}"
39 return match.group()
40
41 return re.sub(_color_pattern, _replace_match_callback, json_str)
42
43
44 def main():
45 description = ('A simple command line interface for json module '
46 'to validate and pretty-print JSON objects.')
47 parser = argparse.ArgumentParser(description=description, color=True)
48 parser.add_argument('infile', nargs='?',
49 help='a JSON file to be validated or pretty-printed',
50 default='-')
51 parser.add_argument('outfile', nargs='?',
52 help='write the output of infile to outfile',
53 default=None)
54 parser.add_argument('--sort-keys', action='store_true', default=False,
55 help='sort the output of dictionaries alphabetically by key')
56 parser.add_argument('--no-ensure-ascii', dest='ensure_ascii', action='store_false',
57 help='disable escaping of non-ASCII characters')
58 parser.add_argument('--json-lines', action='store_true', default=False,
59 help='parse input using the JSON Lines format. '
60 'Use with --no-indent or --compact to produce valid JSON Lines output.')
61 group = parser.add_mutually_exclusive_group()
62 group.add_argument('--indent', default=4, type=int,
63 help='separate items with newlines and use this number '
64 'of spaces for indentation')
65 group.add_argument('--tab', action='store_const', dest='indent',
66 const='\t', help='separate items with newlines and use '
67 'tabs for indentation')
68 group.add_argument('--no-indent', action='store_const', dest='indent',
69 const=None,
70 help='separate items with spaces rather than newlines')
71 group.add_argument('--compact', action='store_true',
72 help='suppress all whitespace separation (most compact)')
73 options = parser.parse_args()
74
75 dump_args = {
76 'sort_keys': options.sort_keys,
77 'indent': options.indent,
78 'ensure_ascii': options.ensure_ascii,
79 }
80 if options.compact:
81 dump_args['indent'] = None
82 dump_args['separators'] = ',', ':'
83
84 try:
85 if options.infile == '-':
86 infile = sys.stdin
87 else:
88 infile = open(options.infile, encoding='utf-8')
89 try:
90 if options.json_lines:
91 lines = infile.readlines()
92 objs = (json.loads(line) for line in lines)
93 else:
94 objs = (json.load(infile),)
95 finally:
96 if infile is not sys.stdin:
97 infile.close()
98
99 if options.outfile is None:
100 outfile = sys.stdout
101 else:
102 outfile = open(options.outfile, 'w', encoding='utf-8')
103 with outfile:
104 if can_colorize(file=outfile):
105 t = get_theme(tty_file=outfile).syntax
106 for obj in objs:
107 json_str = json.dumps(obj, **dump_args)
108 outfile.write(_colorize_json(json_str, t))
109 outfile.write('\n')
110 else:
111 for obj in objs:
112 json.dump(obj, outfile, **dump_args)
113 outfile.write('\n')
114 except ValueError as e:
115 raise SystemExit(e)
116
117
118 if __name__ == '__main__':
119 try:
120 main()
121 except BrokenPipeError as exc:
122 raise SystemExit(exc.errno)