python - 在 python 中使用 ASCII 颜色漂亮地打印 JSON

标签 python json pretty-print

我希望在 python 中使用 ASCII 颜色将 JSON 打印到命令行。例如,(出色的)jq 实用程序将使用粗体 ASCII 颜色对 JSON 进行着色,如下所示:

  • 输入:curl --silent http://coinabul.com/api.php | jq .
  • 输出:
    jq output

有谁知道如何用 Python 实现这种效果?几个 SO 问题提供了一些关于使用来自 python 的 ASCII 颜色的很好的信息(例如 Print in terminal with colors using Python? ),但我认为这种效果需要以不同的方式将 pretty-print 器与着色机器结合起来。

最佳答案

使用Pygments图书馆:

import json
from pygments import highlight
from pygments.lexers import JsonLexer
from pygments.formatters import TerminalFormatter

json_object = json.loads('{"foo":"bar"}')
json_str = json.dumps(json_object, indent=4, sort_keys=True)
print(highlight(json_str, JsonLexer(), TerminalFormatter()))

关于python - 在 python 中使用 ASCII 颜色漂亮地打印 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26459749/

相关文章:

javascript - 高效的实时 HTML 表格

python - 忽略 python 中的 SonarQube 警告

android - JSONArray 在不同设备上的奇怪输出

java - Android Web 服务客户端 (JSON)

python - lxml pretty_print python内存过载

c++ - Git Diff Indent/Pretty Print/Beautify Before Diff

python - django批量创建忽略重复项

python - SQLite python executemany() 搞砸了? "can only execute DML statements"

python - 查找给定大小的每个连续子数组的最大值

python - Windows、Eclipse、Pretty Printers - ImportError : No module named _gdb