在Python中为JSON输出着色

37 投票
4 回答
18985 浏览
提问于 2025-04-19 13:03

在Python中,如果我有一个JSON对象obj,我可以这样做:

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

这样可以让这个对象的输出看起来更漂亮。有没有办法让输出更好看一点呢?比如说:加一些颜色?就像[1]的结果那样。

cat foo.json | jq '.'

[1] jq,一个处理JSON的瑞士军刀工具箱:http://stedolan.github.io/jq/

4 个回答

1

对于Python3:

#!/usr/bin/python3
#coding: utf-8

from pygments import highlight, lexers, formatters
import json

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

formatted_json = json.dumps(d, indent=4)
colorful_json = highlight(formatted_json, lexers.JsonLexer(), formatters.TerminalFormatter())
print(colorful_json)
8

这个被认可的答案在最近版本的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)
9

我喜欢使用rich这个库,它需要依赖另一个叫pyments的库。这个库可以满足你在控制台上所有的颜色需求,比如在使用pip时显示进度条,还能自动格式化json数据。你可以看看下面这张图:

enter image description here
62

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

输出示例:

Pygments 上色代码的输出示例

撰写回答