python 的数据类型和json相互转换
json 是一种字符串
字典是单引号,
json 用双引号
json.dumps转json
import json s={'key1':'zhanhao','ky2':'DD','姓名':'刘杰'} # print(s) print(json.dumps(s,indent=4,ensure_ascii=False))#dumps 就是转成转成字符串,转成json,用indent缩进,ensure_ascii=False展示中文
json.loads转字典
import json s={'key1':'zhanhao','ky2':'DD','姓名':'刘杰'} json_str = json.dumps (s,indent=4,ensure_ascii=False) print(json_str) dic = json.loads(json_str)#json转字典 print(dic)
#如果出现单引号,json转字典
import json s='''{'key1':"zhanhao","ky2":"DD","姓名":"刘杰"}''' s =json.loads(s) print(s)
说明json格式不对
可以去bejson.com,网站
把json复制过去,可以检查哪里不对
laod使用:
d = {"user":"fds","user1":23,"user3":"名字"}
import json
with open('u2.txt','w',encoding='utf-8') as f:
# result = json.load(f)
json.dump(d,f,ensure_ascii=False,indent=4)