2016-03-16 46 views
3

当使用json.dump保存字典时,它只是单行。我想使这个人类可读的格式,如本网站 - https://jsonformatter.curiousconcept.com将字典保存为JSON,以便它们可以被人读取

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

具体来说,是否有一个可接受的默认方式来直接在python中做到这一点?

+0

https://docs.python.org/2/library/json.html – RPGillespie

+2

http://stackoverflow.com/questions/12943819/how-to-python-prettyprint-a -json-file – RPGillespie

+0

http://stackoverflow.com/questions/352098/how-can-i-pretty-print-json – RPGillespie

回答

5

您应该使用json module中的indentseparators参数。从文档有:

>>> import json 
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, 
...     indent=4, separators=(',', ': ')) 
{ 
    "4": 5, 
    "6": 7 
} 
相关问题