Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中为JSON输出着色_Python_Json - Fatal编程技术网

在python中为JSON输出着色

在python中为JSON输出着色,python,json,Python,Json,在python中,如果我有一个JSON对象obj,那么我可以 print json.dumps(obj, sort_keys=True, indent=4) 为了得到一个漂亮的打印输出的对象。是否有可能进一步美化输出:特别添加一些颜色?类似于[1]的结果 cat foo.json | jq '.' [1] jqJSON瑞士陆军工具箱:您可以使用它为JSON输出着色。根据您所拥有的: formatted_json = json.dumps(obj, sort_keys=True, indent

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

print json.dumps(obj, sort_keys=True, indent=4)
为了得到一个漂亮的打印输出的对象。是否有可能进一步美化输出:特别添加一些颜色?类似于[1]的结果

cat foo.json | jq '.'
[1]
jq
JSON瑞士陆军工具箱:

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

什么是
jq
?它有什么用?也许有什么用,买吧我不知道exactly@Tichodroma:加入reference@stalk:我希望将其集成到脚本中,以便控制台的输出将被着色。这是完全可能的(您可以将此
jq
称为Python的子进程),但如果您要求:“内置json库有没有办法做到这一点”然后答案是“没有”。我需要什么来避免
name错误:没有定义名称“unicode”
?那么您使用的是python 3,只需使用
coloric\u json=highlight(格式化的\u json,lexers.JsonLexer(),formatters.TerminalFormatter())
如何在Windows上实现此功能?
名称错误:未定义名称“unicode”
-->
导入unicode