python將字典內(nèi)容寫入json文件的實例代碼
python將字典內(nèi)容寫入json文件的方法:我們可以先使用json.dumps()函數(shù)將字典轉(zhuǎn)換為字符串;然后再將內(nèi)容寫入json即可。json.dumps()函數(shù)負(fù)責(zé)對數(shù)據(jù)進(jìn)行編碼。
字典內(nèi)容寫入json時,需要用json.dumps將字典轉(zhuǎn)換為字符串,然后再寫入。
json也支持格式,通過參數(shù)indent可以設(shè)置縮進(jìn),如果不設(shè)置的話,則保存下來會是一行。
舉例:
無縮進(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文件的實例代碼的詳細(xì)內(nèi)容,更多關(guān)于python如何將字典內(nèi)容寫入json文件的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. HTTP協(xié)議常用的請求頭和響應(yīng)頭響應(yīng)詳解說明(學(xué)習(xí))2. Vue如何使用ElementUI對表單元素進(jìn)行自定義校驗及踩坑3. react實現(xiàn)組件狀態(tài)緩存的示例代碼4. React優(yōu)雅的封裝SvgIcon組件示例5. HTML DOM setInterval和clearInterval方法案例詳解6. HTML5實戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)7. HTML5 Canvas繪制圖形從入門到精通8. CSS清除浮動方法匯總9. XML入門的常見問題(三)10. 不要在HTML中濫用div
