python - 在python中为JSON输出着色

标签 python json

在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/

最佳答案

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

关于python - 在python中为JSON输出着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25638905/

相关文章:

python - 检查文件的名称是否具有相同的日期,Python 3

javascript - Python 异步代码中的 Promise.race 等价物是什么?

python - 如何使用python识别图像中是否存在实心圆?

python - 在Python中对地理编码/(纬度/经度)数据点进行聚类分析的最佳方法是什么?

c# - JSON Youtube反序列化:如何保留Description字段的\n

javascript - 使用 React 漂亮地打印 JSON

python - 如何在python中获取用逗号分隔的数字组?

json - Swift 如何从 JSON 中提取 "sort"字典以在时间序列中绘制它?

Android:带空格的 Json 字符串给出 "Unterminated object at"异常

json - Groovy:将数组转换为JSon