python - 在 Python 中格式化 JSON
问题描述
当初始 JSON 字符串被格式化而没有额外的空格或换行符时,将 JSON 字符串漂亮地打印为带有缩进的字符串的最简单方法是什么?
目前我正在运行json.loads()
,然后运行json.dumps()
结果indent=2
。这行得通,但感觉就像我在浪费大量计算资源。
是否有更简单或更高效(内置)的方式来漂亮地打印 JSON 字符串?(同时保持它为有效的 JSON)
例子
import requests
import json
response = requests.get('http://spam.eggs/breakfast')
one_line_json = response.content.decode('utf-8')
pretty_json = json.dumps(json.loads(response.content), indent=2)
print(f'Original: {one_line_json}')
print(f'Pretty: {pretty_json}')
输出:
Original: {"breakfast": ["spam", "spam", "eggs"]}
Pretty: {
"breakfast": [
"spam",
"spam",
"eggs"
]
}
解决方案
json.dumps(obj, indent=2)
比pprint
因为:
- 使用相同的加载方法会更快。
- 它具有相同或相似的简单性。
- 输出将产生有效的 JSON,而
pprint
不会。
pprint_vs_dumps.py
import cProfile
import json
import pprint
from urllib.request import urlopen
def custom_pretty_print():
url_to_read = "https://www.cbcmusic.ca/Component/Playlog/GetPlaylog?stationId=96&date=2018-11-05"
with urlopen(url_to_read) as resp:
pretty_json = json.dumps(json.load(resp), indent=2)
print(f'Pretty: {pretty_json}')
def pprint_json():
url_to_read = "https://www.cbcmusic.ca/Component/Playlog/GetPlaylog?stationId=96&date=2018-11-05"
with urlopen(url_to_read) as resp:
info = json.load(resp)
pprint.pprint(info)
cProfile.run('custom_pretty_print()')
>>> 71027 function calls (42309 primitive calls) in 0.084 seconds
cProfile.run('pprint_json()')
>>>164241 function calls (140121 primitive calls) in 0.208 seconds
感谢@tobias_k 在此过程中指出我的错误。
推荐阅读
- nginx - 在 Nginx PHP 虚拟主机上设置字符集不起作用
- angular - 仍然需要 Angular 服务模块吗?
- python - Opencv/Python 可执行文件创建问题
- javascript - 我们是否需要在生产结束时捆绑我们的 js 文件
- java - 三个文件中的匹配编号未显示
- c++ - 为什么我使用 fstream 的输出不好?
- ruby-on-rails - Rails:如何检查用户是否存在于控制器中,如果不重定向到其他站点
- java - 与 Spring-Boot 同时提供 JSON 响应和下载文件
- swift - 在选项卡控制器中禁用除主页之外的所有按钮
- ios - 从服务器加载图像到标签栏项目