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)