python接口测试之序列化与反序列化(四)
在python中,序列化可以理解为:把python的对象编码转换为json格式的字符串,反序列化可以理解为:把json格式
字符串解码为python数据对象。在python的标准库中,专门提供了json库与pickle库来处理这部分。
先来学习json的库,导入json库很简单,直接import json,下面通过具体的实例来说明json库对序列化与反序列化的使用。json库的主要方法为:
#!/usr/bin/env python
#coding:utf-8 import json print json.__all__
见json库的主要方法:
['dump', 'dumps', 'load', 'loads', 'JSONDecoder', 'JSONEncoder']
我们定义一个字典,通过json把它序列化为json格式的字符串,见实现的代码:

#!/usr/bin/env python
#coding:utf-8 import json dict1={'name':'wuya','age':22,'address':'xian'} print u'未序列化前的数据类型为:',type(dict1)
print u'未序列化前的数据:',dict1
#对dict1进行序列化的处理
str1=json.dumps(dict1)
print u'序列化后的数据类型为:',type(str1)
print u'序列化后的数据为:',str1

见如上的代码输出的内容:
1
2
3
4
5
6
7
|
C:\Python27\python.exe D: / git / Python / doc / index.py 未序列化前的数据类型为: < type 'dict' > 未序列化前的数据: { 'age' : 22 , 'name' : 'wuya' , 'address' : 'xian' } 序列化后的数据类型为: < type 'str' > 序列化后的数据为: { "age" : 22 , "name" : "wuya" , "address" : "xian" } Process finished with exit code 0 |
通过如上的代码以及结果可以看到,这就是一个序列化的过程,简单的说就是把python的数据类型转换为json格式的
字符串。下来我们再反序列化,把json格式的字符串解码为python的数据对象,见实现的代码和输出:

#!/usr/bin/env python
#coding:utf-8 import json dict1={'name':'wuya','age':22,'address':'xian'} print u'未序列化前的数据类型为:',type(dict1)
print u'未序列化前的数据:',dict1
#对dict1进行序列化的处理
str1=json.dumps(dict1)
print u'序列化后的数据类型为:',type(str1)
print u'序列化后的数据为:',str1
#对str1进行反序列化
dict2=json.loads(str1)
print u'反序列化后的数据类型:',type(dict2)
print u'反序列化后的数据:',dict2

见输出结果的内容:

C:\Python27\python.exe D:/git/Python/doc/index.py
未序列化前的数据类型为: <type 'dict'>
未序列化前的数据: {'age': 22, 'name': 'wuya', 'address': 'xian'}
序列化后的数据类型为: <type 'str'>
序列化后的数据为: {"age": 22, "name": "wuya", "address": "xian"}
反序列化后的数据类型: <type 'dict'>
反序列化后的数据: {u'age': 22, u'name': u'wuya', u'address': u'xian'}

下面我们结合requests库,来看返回的json数据,具体代码为:

#!/usr/bin/env python
#coding:utf-8 import json
import requests r=requests.get('http://wthrcdn.etouch.cn/weather_mini?city=西安') print r.text,u'数据类型:',type(r.text)
#对数据进行反序列化的操作
dic=json.loads(r.text)
print dic,u'数据类型:',type(dic)

见输出的内容:

C:\Python27\python.exe D:/git/Python/doc/index.py
{"desc":"OK","status":1000,"data":{"wendu":"3","ganmao":"昼夜温差较大,较易发生感冒,请适当增减衣服。体质较弱的朋友请注意防护。","forecast":[{"fengxiang":"东北风","fengli":"微风级","high":"高温 10℃","type":"晴","low":"低温 -2℃","date":"22日星期四"},{"fengxiang":"东北风","fengli":"微风级","high":"高温 8℃","type":"多云","low":"低温 0℃","date":"23日星期五"},{"fengxiang":"东北风","fengli":"微风级","high":"高温 7℃","type":"阴","low":"低温 0℃","date":"24日星期六"},{"fengxiang":"东北风","fengli":"微风级","high":"高温 1℃","type":"雨夹雪","low":"低温 -1℃","date":"25日星期天"},{"fengxiang":"东北风","fengli":"微风级","high":"高温 5℃","type":"多云","low":"低温 1℃","date":"26日星期一"}],"yesterday":{"fl":"微风","fx":"北风","high":"高温 7℃","type":"阴","low":"低温 -1℃","date":"21日星期三"},"aqi":"87","city":"西安"}} 数据类型: <type 'unicode'>
{u'status': 1000, u'data': {u'city': u'\u897f\u5b89', u'yesterday': {u'fx': u'\u5317\u98ce', u'type': u'\u9634', u'high': u'\u9ad8\u6e29 7\u2103', u'low': u'\u4f4e\u6e29 -1\u2103', u'date': u'21\u65e5\u661f\u671f\u4e09', u'fl': u'\u5fae\u98ce'}, u'forecast': [{u'fengxiang': u'\u4e1c\u5317\u98ce', u'high': u'\u9ad8\u6e29 10\u2103', u'fengli': u'\u5fae\u98ce\u7ea7', u'date': u'22\u65e5\u661f\u671f\u56db', u'type': u'\u6674', u'low': u'\u4f4e\u6e29 -2\u2103'}, {u'fengxiang': u'\u4e1c\u5317\u98ce', u'high': u'\u9ad8\u6e29 8\u2103', u'fengli': u'\u5fae\u98ce\u7ea7', u'date': u'23\u65e5\u661f\u671f\u4e94', u'type': u'\u591a\u4e91', u'low': u'\u4f4e\u6e29 0\u2103'}, {u'fengxiang': u'\u4e1c\u5317\u98ce', u'high': u'\u9ad8\u6e29 7\u2103', u'fengli': u'\u5fae\u98ce\u7ea7', u'date': u'24\u65e5\u661f\u671f\u516d', u'type': u'\u9634', u'low': u'\u4f4e\u6e29 0\u2103'}, {u'fengxiang': u'\u4e1c\u5317\u98ce', u'high': u'\u9ad8\u6e29 1\u2103', u'fengli': u'\u5fae\u98ce\u7ea7', u'date': u'25\u65e5\u661f\u671f\u5929', u'type': u'\u96e8\u5939\u96ea', u'low': u'\u4f4e\u6e29 -1\u2103'}, {u'fengxiang': u'\u4e1c\u5317\u98ce', u'high': u'\u9ad8\u6e29 5\u2103', u'fengli': u'\u5fae\u98ce\u7ea7', u'date': u'26\u65e5\u661f\u671f\u4e00', u'type': u'\u591a\u4e91', u'low': u'\u4f4e\u6e29 1\u2103'}], u'ganmao': u'\u663c\u591c\u6e29\u5dee\u8f83\u5927\uff0c\u8f83\u6613\u53d1\u751f\u611f\u5192\uff0c\u8bf7\u9002\u5f53\u589e\u51cf\u8863\u670d\u3002\u4f53\u8d28\u8f83\u5f31\u7684\u670b\u53cb\u8bf7\u6ce8\u610f\u9632\u62a4\u3002', u'wendu': u'3', u'aqi': u'87'}, u'desc': u'OK'} 数据类型: <type 'dict'> Process finished with exit code 0

事实上,在如上的代码中,我们可以不通过反序列化的操作,代码可以简化为:

#!/usr/bin/env python
#coding:utf-8 import json
import requests r=requests.get('http://wthrcdn.etouch.cn/weather_mini?city=西安')
print r.json(),u'数据类型为:',type(r.json())

见输出的内容:

C:\Python27\python.exe D:/git/Python/doc/index.py
{u'status': 1000, u'data': {u'city': u'\u897f\u5b89', u'yesterday': {u'fx': u'\u5317\u98ce', u'type': u'\u9634', u'high': u'\u9ad8\u6e29 7\u2103', u'low': u'\u4f4e\u6e29 -1\u2103', u'date': u'21\u65e5\u661f\u671f\u4e09', u'fl': u'\u5fae\u98ce'}, u'forecast': [{u'fengxiang': u'\u4e1c\u5317\u98ce', u'high': u'\u9ad8\u6e29 10\u2103', u'fengli': u'\u5fae\u98ce\u7ea7', u'date': u'22\u65e5\u661f\u671f\u56db', u'type': u'\u6674', u'low': u'\u4f4e\u6e29 -2\u2103'}, {u'fengxiang': u'\u4e1c\u5317\u98ce', u'high': u'\u9ad8\u6e29 8\u2103', u'fengli': u'\u5fae\u98ce\u7ea7', u'date': u'23\u65e5\u661f\u671f\u4e94', u'type': u'\u591a\u4e91', u'low': u'\u4f4e\u6e29 0\u2103'}, {u'fengxiang': u'\u4e1c\u5317\u98ce', u'high': u'\u9ad8\u6e29 7\u2103', u'fengli': u'\u5fae\u98ce\u7ea7', u'date': u'24\u65e5\u661f\u671f\u516d', u'type': u'\u9634', u'low': u'\u4f4e\u6e29 0\u2103'}, {u'fengxiang': u'\u4e1c\u5317\u98ce', u'high': u'\u9ad8\u6e29 1\u2103', u'fengli': u'\u5fae\u98ce\u7ea7', u'date': u'25\u65e5\u661f\u671f\u5929', u'type': u'\u96e8\u5939\u96ea', u'low': u'\u4f4e\u6e29 -1\u2103'}, {u'fengxiang': u'\u4e1c\u5317\u98ce', u'high': u'\u9ad8\u6e29 5\u2103', u'fengli': u'\u5fae\u98ce\u7ea7', u'date': u'26\u65e5\u661f\u671f\u4e00', u'type': u'\u591a\u4e91', u'low': u'\u4f4e\u6e29 1\u2103'}], u'ganmao': u'\u663c\u591c\u6e29\u5dee\u8f83\u5927\uff0c\u8f83\u6613\u53d1\u751f\u611f\u5192\uff0c\u8bf7\u9002\u5f53\u589e\u51cf\u8863\u670d\u3002\u4f53\u8d28\u8f83\u5f31\u7684\u670b\u53cb\u8bf7\u6ce8\u610f\u9632\u62a4\u3002', u'wendu': u'3', u'aqi': u'87'}, u'desc': u'OK'} 数据类型为: <type 'dict'> Process finished with exit code 0

在实际的工作中,序列化或者反序列化的可能是一个文件的形式,不可能像如上写的那样简单的,下来就来实现这部分,把文件内容
进行序列化和反序列化,先来看序列化的代码:

#!/usr/bin/env python
#coding:utf-8 import json list1=['selenium','appium','android','ios','uiautomator']
#把list1先序列化,再写入到一个文件中
print json.dump(list1,open('c:/log.log','w'))
print u'文件内容为:'
r=open('c:/log.log','r+')
print r.read()

见输出的内容:
C:\Python27\python.exe D:/git/Python/doc/index.py
None
文件内容为:
["selenium", "appium", "android", "ios", "uiautomator"] Process finished with exit code 0
下面我们来反序列化,也就是先读取文件里面的内容,再进行反序列化,见实现的代码:

#!/usr/bin/env python
#coding:utf-8 import json list1=['selenium','appium','android','ios','uiautomator']
#把list1先序列化,再写入到一个文件中
print json.dump(list1,open('c:/log.log','w'))
print u'文件内容为:'
r=open('c:/log.log','r+')
print r.read()
#先读取文件内容,再进行反序列化
res=json.load(open('c:/log.log','r+'))
print res,u'数据类型:',type(res)

见输出的内容:

C:\Python27\python.exe D:/git/Python/doc/index.py
None
文件内容为:
["selenium", "appium", "android", "ios", "uiautomator"]
[u'selenium', u'appium', u'android', u'ios', u'uiautomator'] 数据类型: <type 'list'> Process finished with exit code 0

下来来看pickle库,它提供的方法为:
#!/usr/bin/env python
#coding:utf-8 import pickle print pickle.__all__

C:\Python27\python.exe D:/git/Python/doc/index.py
['PickleError', 'PicklingError', 'UnpicklingError', 'Pickler', 'Unpickler', 'dump', 'dumps', 'load', 'loads', 'APPEND', 'APPENDS', 'BINFLOAT', 'BINGET', 'BININT', 'BININT1', 'BININT2', 'BINPERSID', 'BINPUT', 'BINSTRING', 'BINUNICODE', 'BUILD', 'DICT', 'DUP', 'EMPTY_DICT', 'EMPTY_LIST', 'EMPTY_TUPLE', 'EXT1', 'EXT2', 'EXT4', 'FALSE', 'FLOAT', 'GET', 'GLOBAL', 'HIGHEST_PROTOCOL', 'INST', 'INT', 'LIST', 'LONG', 'LONG1', 'LONG4', 'LONG_BINGET', 'LONG_BINPUT', 'MARK', 'NEWFALSE', 'NEWOBJ', 'NEWTRUE', 'NONE', 'OBJ', 'PERSID', 'POP', 'POP_MARK', 'PROTO', 'PUT', 'REDUCE', 'SETITEM', 'SETITEMS', 'SHORT_BINSTRING', 'STOP', 'STRING', 'TRUE', 'TUPLE', 'TUPLE1', 'TUPLE2', 'TUPLE3', 'UNICODE'] Process finished with exit code 0

这里我们只关注pickle库的dump(),dumps(),load(),loads()方法,先来看序列化的代码:
import pickle dic={'name':'无涯','age':22,'address':'西安'}
str1=pickle.dumps(dic)
print str1,type(str1)
见输出的内容:

C:\Python27\python.exe D:/git/Python/doc/index.py
(dp0
S'age'
p1
I22
sS'name'
p2
S'\xe6\x97\xa0\xe6\xb6\xaf'
p3
sS'address'
p4
S'\xe8\xa5\xbf\xe5\xae\x89'
p5
s. <type 'str'>

输出的内容基本看不懂,但是可以看到数据格式是字符串,这是ASCII格式的数据,默认是ASCII格式保存对象,
在进行序列化的使用,设置为True就是二进制保存对象,见实现的代码和输出内容:

#!/usr/bin/env python
#coding:utf-8 import pickle dic={'name':'无涯','age':22,'address':'西安'}
str1=pickle.dumps(dic,True)
print str1,type(str1)

见输出的二进制的数据:
C:\Python27\python.exe D:/git/Python/doc/index.py
}q (UageqKUnameqU无涯qUaddressqU西安qu. <type 'str'>
下面通过loads()方法来进行反序列化,见实现的代码:

#!/usr/bin/env python
#coding:utf-8 import pickle dic={'name':u'无涯','age':22,'address':u'西安'}
#序列化
str1=pickle.dumps(dic,True)
print str1,type(str1)
#反序列化
dict1=pickle.loads(str1)
print dict1,type(dict1)

见输出的内容:
C:\Python27\python.exe D:/git/Python/doc/index.py
}q (UageqKUnameqX 无涯qUaddressqX 西安qu. <type 'str'>
{'age': 22, 'name': u'\u65e0\u6daf', 'address': u'\u897f\u5b89'} <type 'dict'>
下来我们通过对文件的形式来进行序列化和反序列化,见实现的代码:

#!/usr/bin/env python
#coding:utf-8 import pickle dic={'name':u'无涯','age':22,'address':u'西安'}
#先序列化,然后写入到文件中
pickle.dump(dic,open('c:/log.log','w'),True)
print u'文件内容为:'
print open('c:/log.log').read()
#先读取文件,再反序列化
d=pickle.load(open('c:/log.log','r+'))
print u'反序列化后的数据与数据类型:',d,type(d)

见输出的内容:
C:\Python27\python.exe D:/git/Python/doc/index.py
文件内容为:
}q (UageqKUnameqX 无涯qUaddressqX 西安qu.
反序列化后的数据与数据类型: {'age': 22, 'name': u'\u65e0\u6daf', 'address': u'\u897f\u5b89'} <type 'dict'> Process finished with exit code 0
python接口测试之序列化与反序列化(四)的更多相关文章
- python类库32[序列化和反序列化之pickle]
一 pickle pickle模块用来实现python对象的序列化和反序列化.通常地pickle将python对象序列化为二进制流或文件. python对象与文件之间的序列化和反序列化: pi ...
- C#实现接口xml序列化与反序列化
C#实现接口xml序列化与反序列化 C#中接口无法被xml序列化,提示不支持.百度和bing也搜不到,只好自己动手写了 原理上肯定支持,.Net自己的xml序列化有一个IXmlSerializab ...
- python接口测试之mock(二)
上一篇对mock-server已经做了初步的介绍,今天这里继续接着之前的介绍进行,我们先看之前的mock-server部分,之前编写了一个登录的mock,具体json文件见如下的内容: 小王子1110 ...
- Python库:序列化和反序列化模块pickle介绍
1 前言 在“通过简单示例来理解什么是机器学习”这篇文章里提到了pickle库的使用,本文来做进一步的阐述. 通过简单示例来理解什么是机器学习 pickle是python语言的一个标准模块,安装pyt ...
- python中的序列化和反序列化
~~~~~~滴滴,,什么是序列呢?可以理解为序列就是字符串.序列化的应用 写文件(数据传输) 网络传输 序列化和反序列化的概念 序列化模块:将原本的字典.列表等内容转换成一个字符串的过程就叫做序列 ...
- Python开发之序列化与反序列化:pickle、json模块使用详解
1 引言 在日常开发中,所有的对象都是存储在内存当中,尤其是像python这样的坚持一切接对象的高级程序设计语言,一旦关机,在写在内存中的数据都将不复存在.另一方面,存储在内存够中的对象由于编程语言. ...
- 模块讲解----pickle模块(只在python用的序列化与反序列化)
特点 1.只能在python中使用,只支持python的基本数据类型. 2.可以处理复杂的序列化语法.(例如自定义的类的方法,游戏的存档等) 3.序列化的时候,只是序列化了整个序列对象,而不是内存地址 ...
- python marshal 对象序列化和反序列化
有时候,要把内存中的一个对象持久化保存到磁盘上,或者序列化成二进制流通过网络发送到远程主机上.Python中有很多模块提供了序列化与反序列化的功能,如:marshal, pickle, cPickle ...
- Python实现JSON序列化和反序列化
在我的应用中,序列化就是把类转成符合JSON格式的字符串,反序列化就是把JSON格式的字符串转换成类.C#的话直接用Newtonsoft.JSON就可以了,非常好用.本来以为python也会有类似的库 ...
随机推荐
- Canny检测理解和Matlab实现
图象的边缘是指图象局部区域亮度变化显著的部分,该区域的灰度剖面一般可以看作是一个阶跃,既从一个灰度值在很小的缓冲区域内急剧变化到另一个灰度相差较大的灰度值. 1.Canny边缘检测的基本特征 (1) ...
- 使用Apache Commons IO组件读取大文件
Apache Commons IO读取文件代码如下: Files.readLines(new File(path), Charsets.UTF_8); FileUtils.readLines(new ...
- 组合模式和php实现
组合模式(有时候又叫做部分-整体模式): 将对象组合成树形结构以表示“部分整体”的层次结构.组合模式使得用户对单个对象和组合对象的使用具有一致性.它使我们树型结构的问题中,模糊了简单元素和复杂元素的概 ...
- vue-router: $router.push遇到的问题
如下图使用path时,跳转路由后的页面this.$route.params为undefined 改为name时,this.$route.params可以正确获取数据,如下图: 此为官方定义的固定搭配: ...
- mybatis 返回值
转载: 在使用ibatis插入数据进数据库的时候,会用到一些sequence的数据,有些情况下,在插入完成之后还需要将sequence的值返回,然后才能进行下一步的操作. 使用ibatis的 ...
- MAC 添加共享,脚本执行
Linux需要首先安装 yum install samba-client linxu添加windows 公共盘 mount -t cifs user=guest,password=guest // ...
- Windows bat 设置代理
转自tt-0411 @echo off cls color 0A Echo The program is running... Echo Setting the ip and dns... netsh ...
- sql中的日期时间处理
每个数据库,不同的日期格式化: 1.mysql 2.sqlserver 使用Convert()函数: select convert(char(10),GetDate(),120) as Date 第3 ...
- VC++检测硬件设备状态
首先捕捉WM_DEVICECHANGE消息,该消息在usb插拔时均有触发. MFC下 添加消息处理函数afx_msg BOOL OnDeviceChange( UINT nEventType, DWO ...
- js 给url添加时间戳 解决浏览器缓存
//解决浏览器缓存 function timestamp(url){ // var getTimestamp=Math.random(); var getTimestamp=new Dat ...