json與字典相互轉換


1.將字典轉成json

import json

dic = {'name':'wangyujian','sex':'男','age':18}

js = json.dumps(dic,ensure_ascii=False)   # ensure_ascii=False 將字典中的中文編碼轉換一下,不然輸出時顯示的是ASCII碼

print(js)

 

2.將字典轉成json並存放在文件中

import json

dic = {'name':'wangyujian','sex':'男','age':18}

js = open('a.json','w',encoding='utf-8')

json.dump(dic,js,ensure_ascii=False,indent=4)  # indent代表首行縮進多少行

 

3.將json轉成字典

import json

js = '{"name":"wangyujian","sex":"男","age":18}'

dic = json.loads(js)

print(dic)

 

4.從文件中讀取json,並轉化成字典

import json

js = open('a.json','r',enconding='utf-8')

dic = json.load(js)

print(dic)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM