在python中着色JSON输出

Dro*_*ror 23 python json

在python中,如果我有一个JSON对象obj,那么我可以

print json.dumps(obj, sort_keys=True, indent=4)
Run Code Online (Sandbox Code Playgroud)

为了获得对象的漂亮打印输出.是否有可能进一步美化输出:特别添加一些颜色?像[1]的结果

cat foo.json | jq '.'
Run Code Online (Sandbox Code Playgroud)

[1] jqJSON Swiss Army工具箱:http://stedolan.github.io/jq/

arn*_*hky 38

您可以使用Pygments为JSON输出着色.根据你所拥有的:

formatted_json = json.dumps(obj, sort_keys=True, indent=4)

from pygments import highlight, lexers, formatters
colorful_json = highlight(unicode(formatted_json, 'UTF-8'), lexers.JsonLexer(), formatters.TerminalFormatter())
print(colorful_json)
Run Code Online (Sandbox Code Playgroud)

输出示例:

pygments彩色代码的输出示例

  • 然后你使用python 3,应该只使用`colorful_json = highlight(formatted_json,lexers.JsonLexer(),formatters.TerminalFormatter())` (10认同)
  • 为了避免出现NameError:未定义名称“ unicode”,我该怎么办? (3认同)

Mor*_*enB 9

我喜欢使用rich,它依赖于 pyments。但它涵盖了您所有的控制台着色需求,在 pip 中用于显示进度以及自动格式化 json: 在此输入图像描述


Hat*_*ind 5

接受的答案似乎不适用于更新版本的 Pygments 和 Python。所以这里是你如何在 Pygments 2.7.2+ 中做到这一点:

import json
from pygments import highlight
from pygments.formatters.terminal256 import Terminal256Formatter
from pygments.lexers.web import JsonLexer

d = {"test": [1, 2, 3, 4], "hello": "world"}

# Generate JSON
raw_json = json.dumps(d, indent=4)

# Colorize it
colorful = highlight(
    raw_json,
    lexer=JsonLexer(),
    formatter=Terminal256Formatter(),
)

# Print to console
print(colorful)
Run Code Online (Sandbox Code Playgroud)