将dict保存为JSON,以便它们是人类可读的

goe*_*ash 6 python json human-readable

当使用json.dump保存dict时,它只是一个单行.我想让这个像人类可读的格式,如本网站的确 - https://jsonformatter.curiousconcept.com

我怎么能在python中这样做?我试图捕获pprint输出,但它是一个无效的字符串来存储JSON.

具体来说,是否有一种可接受的默认方式直接在python中执行此操作?

Ami*_*ory 8

您应该使用模块中indentseparators参数.从那里的文档:json

>>> import json
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True,
...                  indent=4, separators=(',', ': '))
{
    "4": 5,
    "6": 7
}
Run Code Online (Sandbox Code Playgroud)