字典与json 互转
# json 就是一个字符串
d = {
"username": "xiaoming",
"password":"123456啊"
}
import json
with open('userjson.txt', 'w', encoding='utf-8') as f:
# 把字典转成json字符串,
# ensure_ascii=False:中文不用unicode显示,直接中文显示
# indent=4: 缩进4个空格
# s = json.dumps(d, ensure_ascii=False, indent=4)
# f.write(s)
json.dump(d, f, indent=4, ensure_ascii=False) # 把d字典写入文件f
with open('userjson.txt',encoding='utf-8') as fr:
result = fr.read()
print("result的文件类型",type(result))
dic = json.loads(result) #把json字符串转换成字典
print(dic)
f.seek(0)
result = json.load(fr) #把文件转换成字典
print(result)