python接口自动化学习八之json序列化与反序列化

序列化:把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'])

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值