内容大纲
1: 为什么要学习json模块
>1:因为网络之间的通信,还有不同语言之间的相互内容沟通,需要用到json 模式进行沟通
>2:写入部分文件用json文件保存,
2:json的序列化
json.dumps(iterable)
dic ={'k1':'v1','k2':'v2','k3':'v3'} str_dic =json.dumps(dic) print(str_dic)
>>>>>>
{"k1": "v1", "k2": "v2", "k3": "v3"}
3:将json 转化成字典
json.loads(json模式的内容)
dic ={'k1':'v1','k2':'v2','k3':'v3'} str_dic =json.dumps(dic) # print(str_dic) #将json 转成字典模式 dic1 =json.loads(str_dic) print(dic1)
>>>>>
{'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
4:自动把所有的' ' 变成 " "
json.dumps() 因为json 的模式就是 " "
list_dic =[1,['a','b','c','d'],3,{'k1':'v1','k2':'v2','k3':'v3'}] str =json.dumps(list_dic) print(str)
>>>>>
[1, ["a", "b", "c", "d"], 3, {"k1": "v1", "k2": "v2", "k3": "v3"}]
5:json 写入文件
dump(iteaber,句柄)
dic ={'k1':'v1','k2':'v2','k3':'v3'} # json 写入文件 with open('123.json','w',encoding='utf-8') as f: json.dump(dic,f)
6:读取json文件
json.load(句柄)
with open('123.json','r',encoding='utf-8') as f1: ret =json.load(f1) print(ret)
7:将多个json 写入json文件
将多个json 文件写入文件 dic1 = {'name': '春哥'} dic2 = {'name': '子伍'} dic3 = {'name': '王子'} with open('duo.json','w',encoding='utf-8') as f2: json.dump(dic1,f2) f2.write(' ') json.dump(dic2,f2) f2.write(' ') #注意换行, 因为读的时候是for 循环句柄 json.dump(dic3,f2) f2.write(json.dumps(dic1)+' ') f2.write(json.dumps(dic2)+' ') f2.write(json.dumps(dic3)+' ') with open('duo.json','r',encoding='utf-8') as f3: for line in f3: ret =json.loads(line) print(ret) ret =json.loads(f3.read()) print(ret)
8: