python將字典內(nèi)容寫入json文件的實(shí)例代碼
python將字典內(nèi)容寫入json文件的方法:我們可以先使用json.dumps()函數(shù)將字典轉(zhuǎn)換為字符串;然后再將內(nèi)容寫入json即可。json.dumps()函數(shù)負(fù)責(zé)對(duì)數(shù)據(jù)進(jìn)行編碼。
字典內(nèi)容寫入json時(shí),需要用json.dumps將字典轉(zhuǎn)換為字符串,然后再寫入。
json也支持格式,通過參數(shù)indent可以設(shè)置縮進(jìn),如果不設(shè)置的話,則保存下來會(huì)是一行。
舉例:
無縮進(jìn):
from collections import defaultdict, OrderedDictimport jsonvideo = defaultdict(list)video['label'].append('haha')video['data'].append(234)video['score'].append(0.3)video['label'].append('xixi')video['data'].append(123)video['score'].append(0.7)test_dict = { ’version’: '1.0', ’results’: video, ’explain’: {’used’: True,’details’: 'this is for josn test', }}json_str = json.dumps(test_dict)with open(’test_data.json’, ’w’) as json_file: json_file.write(json_str)
有縮進(jìn):
from collections import defaultdict, OrderedDictimport jsonvideo = defaultdict(list)video['label'].append('haha')video['data'].append(234)video['score'].append(0.3)video['label'].append('xixi')video['data'].append(123)video['score'].append(0.7)test_dict = { ’version’: '1.0', ’results’: video, ’explain’: {’used’: True,’details’: 'this is for josn test', }}json_str = json.dumps(test_dict, indent=4)with open(’test_data.json’, ’w’) as json_file: json_file.write(json_str)
以上就是python將字典內(nèi)容寫入json文件的實(shí)例代碼的詳細(xì)內(nèi)容,更多關(guān)于python如何將字典內(nèi)容寫入json文件的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 利用promise及參數(shù)解構(gòu)封裝ajax請(qǐng)求的方法2. Nginx+php配置文件及原理解析3. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無效問題4. .NET中l(wèi)ambda表達(dá)式合并問題及解決方法5. JSP數(shù)據(jù)交互實(shí)現(xiàn)過程解析6. 淺談python出錯(cuò)時(shí)traceback的解讀7. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解8. Ajax實(shí)現(xiàn)表格中信息不刷新頁面進(jìn)行更新數(shù)據(jù)9. Python importlib動(dòng)態(tài)導(dǎo)入模塊實(shí)現(xiàn)代碼10. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向
