2016-03-16 37 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 
} 
相關問題