Skip to main content
 首页 » 编程设计

python之在 Python 中格式化 JSON

2025年05月04日22emanlee

当初始 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 因为:

  1. 使用相同的加载方法速度更快。
  2. 具有相同或相似的简洁性。
  3. 输出将产生有效的 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 一路指出我的错误。