Python 如何漂亮地打印 JSON 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12943819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to prettyprint a JSON file?
提问by Colleen
I have a JSON file that is a mess that I want to prettyprint-- what's the easiest way to do this in python? I know PrettyPrint takes an "object", which I think can be a file, but I don't know how to pass a file in-- just using the filename doesn't work.
我有一个 JSON 文件,我想要漂亮地打印它——在 python 中执行此操作的最简单方法是什么?我知道 PrettyPrint 需要一个“对象”,我认为它可以是一个文件,但我不知道如何传入文件——仅使用文件名是行不通的。
采纳答案by Blender
The jsonmodule already implements some basic pretty printing with the indentparameter:
该json模块已经使用indent参数实现了一些基本的漂亮打印:
>>> import json
>>>
>>> your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print(json.dumps(parsed, indent=4, sort_keys=True))
[
"foo",
{
"bar": [
"baz",
null,
1.0,
2
]
}
]
To parse a file, use json.load():
要解析文件,请使用json.load():
with open('filename.txt', 'r') as handle:
parsed = json.load(handle)
回答by Gismo Ranas
You can do this on the command line:
您可以在命令行上执行此操作:
python3 -m json.tool some.json
(as already mentioned in the commentaries to the question, thanks to @Kai Petzke for the python3 suggestion).
(正如在问题的评论中已经提到的,感谢@Kai Petzke 的 python3 建议)。
Actually python is not my favourite tool as far as json processing on the command line is concerned. For simple pretty printing is ok, but if you want to manipulate the json it can become overcomplicated. You'd soon need to write a separate script-file, you could end up with maps whose keys are u"some-key" (python unicode), which makes selecting fields more difficult and doesn't really go in the direction of pretty-printing.
实际上,就命令行上的 json 处理而言,python 并不是我最喜欢的工具。对于简单的漂亮打印是可以的,但是如果您想操作 json,它可能会变得过于复杂。您很快就需要编写一个单独的脚本文件,您最终可能会得到键为 u"some-key" (python unicode) 的映射,这使得选择字段更加困难,并且并没有真正朝着漂亮的方向发展-印刷。
You can also use jq:
您还可以使用jq:
jq . some.json
and you get colors as a bonus (and way easier extendability).
并且您可以获得颜色作为奖励(并且更容易扩展)。
Addendum: There is some confusion in the comments about using jq to process large JSON files on the one hand, and having a very large jq program on the other. For pretty-printing a file consisting of a single large JSON entity, the practical limitation is RAM. For pretty-printing a 2GB file consisting of a single array of real-world data, the "maximum resident set size" required for pretty-printing was 5GB (whether using jq 1.5 or 1.6). Note also that jq can be used from within python after pip install jq.
附录:关于一方面使用 jq 处理大型 JSON 文件,另一方面使用非常大的 jq 程序的评论中存在一些混淆。为了漂亮地打印由单个大型 JSON 实体组成的文件,实际限制是 RAM。为了漂亮打印由单个真实世界数据数组组成的 2GB 文件,漂亮打印所需的“最大驻留集大小”为 5GB(无论是使用 jq 1.5 还是 1.6)。还要注意 jq 可以在pip install jq.
回答by Shubham Chaudhary
Pygmentize + Python json.tool = Pretty Print with Syntax Highlighting
Pygmentize + Python json.tool = 带有语法高亮的漂亮打印
Pygmentize is a killer tool. See this.
Pygmentize 是一个杀手级工具。看到这个。
I combine python json.tool with pygmentize
我将 python json.tool 与 pygmentize 结合使用
echo '{"foo": "bar"}' | python -m json.tool | pygmentize -l json
See the link above for pygmentize installation instruction.
有关 pygmentize 安装说明,请参阅上面的链接。
A demo of this is in the image below:
下图对此进行了演示:
回答by zelusp
Use this function and don't sweat having to remember if your JSON is a stror dictagain - just look at the pretty print:
使用这个函数,不必担心你的 JSON 是 astr还是dict再次——看看漂亮的打印:
import json
def pp_json(json_thing, sort=True, indents=4):
if type(json_thing) is str:
print(json.dumps(json.loads(json_thing), sort_keys=sort, indent=indents))
else:
print(json.dumps(json_thing, sort_keys=sort, indent=indents))
return None
pp_json(your_json_string_or_dict)
回答by V P
To be able to pretty print from the command line and be able to have control over the indentation etc. you can set up an alias similar to this:
为了能够从命令行进行漂亮的打印并能够控制缩进等,您可以设置类似于以下内容的别名:
alias jsonpp="python -c 'import sys, json; print json.dumps(json.load(sys.stdin), sort_keys=True, indent=2)'"
And then use the alias in one of these ways:
然后以下列方式之一使用别名:
cat myfile.json | jsonpp
jsonpp < myfile.json
回答by ikreb
You could use the built-in modul pprint (https://docs.python.org/3.6/library/pprint.html).
您可以使用内置模块pprint (https://docs.python.org/3.6/library/pprint.html)。
How you can read the file with json data and print it out.
如何使用 json 数据读取文件并将其打印出来。
import json
import pprint
json_data = None
with open('filename.txt', 'r') as f:
data = f.read()
json_data = json.loads(data)
pprint.pprint(json_data)
回答by David Liu
Here's a simple example of pretty printing JSON to the console in a nice way in Python, without requiring the JSON to be on your computer as a local file:
这是一个简单的示例,它在 Python 中以一种很好的方式将 JSON 漂亮地打印到控制台,而无需将 JSON 作为本地文件存在于您的计算机上:
import pprint
import json
from urllib.request import urlopen # (Only used to get this example)
# Getting a JSON example for this example
r = urlopen("https://mdn.github.io/fetch-examples/fetch-json/products.json")
text = r.read()
# To print it
pprint.pprint(json.loads(text))
回答by Nakamoto
Use pprint: https://docs.python.org/3.6/library/pprint.html
使用 pprint:https://docs.python.org/3.6/library/pprint.html
import pprint
pprint.pprint(json)
print()compared to pprint.pprint()
print()相比 pprint.pprint()
print(json)
{'feed': {'title': 'W3Schools Home Page', 'title_detail': {'type': 'text/plain', 'language': None, 'base': '', 'value': 'W3Schools Home Page'}, 'links': [{'rel': 'alternate', 'type': 'text/html', 'href': 'https://www.w3schools.com'}], 'link': 'https://www.w3schools.com', 'subtitle': 'Free web building tutorials', 'subtitle_detail': {'type': 'text/html', 'language': None, 'base': '', 'value': 'Free web building tutorials'}}, 'entries': [], 'bozo': 0, 'encoding': 'utf-8', 'version': 'rss20', 'namespaces': {}}
pprint.pprint(json)
{'bozo': 0,
'encoding': 'utf-8',
'entries': [],
'feed': {'link': 'https://www.w3schools.com',
'links': [{'href': 'https://www.w3schools.com',
'rel': 'alternate',
'type': 'text/html'}],
'subtitle': 'Free web building tutorials',
'subtitle_detail': {'base': '',
'language': None,
'type': 'text/html',
'value': 'Free web building tutorials'},
'title': 'W3Schools Home Page',
'title_detail': {'base': '',
'language': None,
'type': 'text/plain',
'value': 'W3Schools Home Page'}},
'namespaces': {},
'version': 'rss20'}
回答by p3quod
I think that's better to parse the json before, to avoid errors:
我认为最好先解析json,以避免错误:
def format_response(response):
try:
parsed = json.loads(response.text)
except JSONDecodeError:
return response.text
return json.dumps(parsed, ensure_ascii=True, indent=4)
回答by Andy
I once wrote a prettyjson()function to produce nice-looking output. You can grab the implementation from this repo.
我曾经写过一个prettyjson()函数来产生漂亮的输出。你可以从这个 repo 中获取实现。
The main feature of this function is it tries to keep dict and list items in one line until a certain maxlinelengthis reached. This produces fewer lines of JSON, the output looks more compact and easier to read.
此函数的主要特点是它尝试将 dict 和 list 项保持在一行中,直到maxlinelength达到某个值。这会产生更少的 JSON 行,输出看起来更紧凑且更易于阅读。
You can produce this kind of output for instance:
例如,您可以生成这种输出:
{
"grid": {"port": "COM5"},
"policy": {
"movingaverage": 5,
"hysteresis": 5,
"fan1": {
"name": "CPU",
"signal": "cpu",
"mode": "auto",
"speed": 100,
"curve": [[0, 75], [50, 75], [75, 100]]
}
}
UPD Dec'19: I placed the code into a separate repo, corrected a few bugs and made a few other tweaks.
UPD 19 年 12 月:我将代码放入单独的 repo 中,纠正了一些错误并进行了一些其他调整。


