在python中着色JSON输出

时间:2014-09-03 07:43:54

标签: python json

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

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

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

的结果
cat foo.json | jq '.'

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

2 个答案:

答案 0 :(得分:36)

您可以使用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)

输出示例:

Output example of pygments colored code

答案 1 :(得分:3)

接受的答案似乎不适用于更新版本的 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)
相关问题