summaryrefslogtreecommitdiffstats
path: root/Lib/json/tool.py
diff options
context:
space:
mode:
authorƁukasz Langa <lukasz@langa.pl>2025-05-05 21:45:25 (GMT)
committerGitHub <noreply@github.com>2025-05-05 21:45:25 (GMT)
commitf610bbdf74ea580b14353c6bfd08fd00bcbfa11e (patch)
tree5755794c7c8f2e4c14ad4be9665499311b4db17b /Lib/json/tool.py
parent9cc77aaf9dce6ffa82786dc77f7f83387c857cad (diff)
downloadcpython-f610bbdf74ea580b14353c6bfd08fd00bcbfa11e.zip
cpython-f610bbdf74ea580b14353c6bfd08fd00bcbfa11e.tar.gz
cpython-f610bbdf74ea580b14353c6bfd08fd00bcbfa11e.tar.bz2
gh-133346: Make theming support in _colorize extensible (GH-133347)
Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
Diffstat (limited to 'Lib/json/tool.py')
-rw-r--r--Lib/json/tool.py41
1 files changed, 22 insertions, 19 deletions
diff --git a/Lib/json/tool.py b/Lib/json/tool.py
index de18636..1967817 100644
--- a/Lib/json/tool.py
+++ b/Lib/json/tool.py
@@ -7,7 +7,7 @@ import argparse
import json
import re
import sys
-from _colorize import ANSIColors, can_colorize
+from _colorize import get_theme, can_colorize
# The string we are colorizing is valid JSON,
@@ -17,27 +17,27 @@ from _colorize import ANSIColors, can_colorize
_color_pattern = re.compile(r'''
(?P<key>"(\\.|[^"\\])*")(?=:) |
(?P<string>"(\\.|[^"\\])*") |
+ (?P<number>NaN|-?Infinity|[0-9\-+.Ee]+) |
(?P<boolean>true|false) |
(?P<null>null)
''', re.VERBOSE)
-
-_colors = {
- 'key': ANSIColors.INTENSE_BLUE,
- 'string': ANSIColors.BOLD_GREEN,
- 'boolean': ANSIColors.BOLD_CYAN,
- 'null': ANSIColors.BOLD_CYAN,
+_group_to_theme_color = {
+ "key": "definition",
+ "string": "string",
+ "number": "number",
+ "boolean": "keyword",
+ "null": "keyword",
}
-def _replace_match_callback(match):
- for key, color in _colors.items():
- if m := match.group(key):
- return f"{color}{m}{ANSIColors.RESET}"
- return match.group()
-
+def _colorize_json(json_str, theme):
+ def _replace_match_callback(match):
+ for group, color in _group_to_theme_color.items():
+ if m := match.group(group):
+ return f"{theme[color]}{m}{theme.reset}"
+ return match.group()
-def _colorize_json(json_str):
return re.sub(_color_pattern, _replace_match_callback, json_str)
@@ -100,13 +100,16 @@ def main():
else:
outfile = open(options.outfile, 'w', encoding='utf-8')
with outfile:
- for obj in objs:
- if can_colorize(file=outfile):
+ if can_colorize(file=outfile):
+ t = get_theme(tty_file=outfile).syntax
+ for obj in objs:
json_str = json.dumps(obj, **dump_args)
- outfile.write(_colorize_json(json_str))
- else:
+ outfile.write(_colorize_json(json_str, t))
+ outfile.write('\n')
+ else:
+ for obj in objs:
json.dump(obj, outfile, **dump_args)
- outfile.write('\n')
+ outfile.write('\n')
except ValueError as e:
raise SystemExit(e)