【Python接口测试】04_序列化和反序列化

概念:

  • 序列化:把 python 的对象编码转换为 json 格式的字符串
  • 反序列化:将 json 格式的字符串解码为 python 数据对象

1.将字典 dict 序列化为 json 格式的字符串

import json

print('json_methods: ', json.__all__)

dict1 = {
    'name': 'A',
    'age': 25,
    'job': 'IT'
}
def dict_to_json():
    print('dict1_origin_type: ', type(dict1))
    print('dict1_origin: ', dict1)

    json1 = json.dumps(dict1)
    print('json1_type: ', type(json1))
    print('json1: ', json1)
dict_to_json()
  1. 将 json 格式的字符串解码为 python 的数据对象
dict2 = {
    'name': 'xk',
    'age': 25,
    'sex': 'male'
}
def json_to_dict():
    print('dict2_origin_type: ', type(dict2))
    print('dict2: ', dict2)

    # 将 dict2 序列化处理
    json2 = json.dumps(dict2)
    print('json2_type: ', type(json2))
    print('json2: ', json2)

    # 对 json2 进行反序列化处理
    dict21 = json.loads(json2)
    print('dict21_type: ', type(dict21))
    print('dict21: ', dict21)
json_to_dict()

3.使用 requests 查看你返回的 json 数据

# 用 requests 查看返回的 json 数据
def requests_get_jsondata():
    r = requests.get('http://wthrcdn.etouch.cn/weather_mini?city=北京')
    print('r_text_type: ', type(r.text))
    print('r_text: ', r.text)

    # 对数据进行反序列化操作(json_to_dict)
    r_json = json.dumps(r.text)
    print('r_json_type: ', type(r_json))
    print('r_json: ', r_json)
requests_get_jsondata()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值