首页 > 解决方案 > 在 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"
    ]
}

标签: pythonjsonpython-3.x

解决方案


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 在此过程中指出我的错误。


推荐阅读