序列化:把python的数据类型转化为str类型,dict->json格式的字符串 。dumps
反序列化:把str类型转为python的数据类型,json格式的字符串->dict。loads
1,字典的序列化与反序列化。
import json
dict1={'name':'wuya','age':18}
#序列化
dict1_str=json.dumps(dict1)
print(dict1_str,type(dict1_str))
#反序列化
str_dict1=json.loads(dict1_str)
print(str_dict1,type(str_dict1))
2,列表的序列化与反序列化
import json
#列表的序列化与反序列化
list1=['admin','wuya','weike']
list1_str=json.dumps(list1)
print("列表序列化后的结果:",list1_str,type(list1_str))
str_list1=json.loads(list1_str)
print("列表反序列化后的结果:",str_list1,type(str_list1))
3,元组的序列化与反序列化
import json
tuple1=(1,2,3)
tuple1_str=json.dumps(tuple1)
print("元组序列化后的结果:",tuple1_str,type(tuple1_str))
str_tuple=json.loads(tuple1_str)
print("反序列化后的结果:",str_tuple,type(str_tuple))
运行结果:
元组序列化后的结果: [1, 2, 3] <class 'str'>
反序列化后的结果: [1, 2, 3] <class 'list'>
实例
import json
import requests
r=requests.post(url='https://ecapi.parkingwang.com/v5/login',
data={"username":"","password":""},
headers={'Parkingwang-Client-Source':'ParkingWangAPIClientWeb','Content-Type':'application/json;charset=UTF-8'})
print(r.status_code)
print(r.text)
print(type(r.text))
print(json.loads(r.text)['msg'])
4,对文件的序列化与反序列化。dump load
import json
import requests
r=requests.get(url='http://www.weather.com.cn/data/sk/101190408.html')
print(r.text)
#因为上述返回的是乱码,所以需要对响应内容进行解码
print(r.content.decode('utf-8'))
#常用的文件写入
# with open('weather.json','w') as f:
# f.write(r.content.decode('utf-8'))
#对文件进行序列化-->就是把服务器的响应数据写到文件中
json.dump(r.content.decode('utf-8'),open('weather.json','w'))
#对文件的反序列化-->就是读取文件的内容
dict1=json.load(open('weather.json','r'))
print(dict1,type(dict1))
dict2=json.loads(dict1) #再进行反序列化字符串类型转为字典类型
print(dict2,type(dict2))
print(dict2['weatherinfo']['city'])