序列化模块-json、pickle、shelve

什么是序列化?
在我们存储数据或者网络传输数据的时候. 需要对我们的对象进行处理. 把对象处理成方便存储和传输的数据格式. 这个过程叫序列化.
不同的序列化, 结果也不同. 但是目的是一样的. 都是为了存储和传输.
在python中存在三种序列列化的方案.
1. pickle. 可以将我们python中的任意数据类型转化成bytes并写入到文件中. 同样也可以把文件中写好的bytes转换回我们python的数据. 这个过程被称为反序列列化
2. shelve. 简单另类的一种序列化的方案. 有点儿类似redis. 可以作为一种小型的数据库来使用
3. json. 将python中常见的字典,列表转化成字符串. 是目前后端数据交互使用频率最高的一种数据格式.
数据结构-->字符串(bytes),序列化
字符串(bytes)-->数据结构,反序列化
dumps     序列化。 把对象转化成bytes
loads   反序列化。 把bytes转化成对象
dump   序列化。 把对象转化成bytes并写入文件
load   反序列化。把文件中的bytes读取。转化成对象

json  数字 字符串 列表 字典 元组
通用的序列化格式
只有很少的一部分数据类型能够通过json转化成字符串
处理中文 ensure_ascii = False

 1 import json
 2 
 3 a = ['qwe', '阿达', '123']
 4 b = json.dumps(a, ensure_ascii=False)
 5 # ensure_ascii=False,包含非ascii的字符
 6 print(b, type(b))
 7 c = json.loads(b)
 8 print(c, type(c))
 9 with open('11', 'w', encoding='utf-8') as f:
10     json.dump(a, f, ensure_ascii=False)
11 #     dump,load接受一个文件句柄,直接输出输入在文件
12 with open('11', 'r', encoding='utf-8') as f:
13     print(json.load(f))
14 
15 # 注意. 我们可以向同一个文件中写入多个json串. 但是读不行.
16 # dump load
17 # with open('11', 'w', encoding='utf-8') as f:
18 #     json.dump('123',f)
19 #     json.dump('123',f)
20 #     json.dump('123',f)
21 # with open('11', 'r', encoding='utf-8') as f:
22 #     print(json.load(f))     # 报错
23 
24 # dumps,loads
25 with open('11', 'w', encoding='utf-8') as f:
26     s = json.dumps('123')
27     f.write(s + '\n')
28     f.write(s + '\n')
29     f.write(s + '\n')
30 with open('11', 'r', encoding='utf-8') as f:
31     for line in f:
32         print(json.loads(line.strip()))
33 
34 '''
35 json其他参数
36 Serialize obj to a JSON formatted str.(字符串表示的json对象)
37 Skipkeys:默认值是False,如果dict的keys内的数据不是python的基本类型(str,unicode,int,long,float,bool,None),设置为False时,就会报TypeError的错误。此时设置成True,则会跳过这类key
38 ensure_ascii:,当它为True的时候,所有非ASCII码字符显示为\ uXXXX序列,只需在dump时将ensure_ascii设置为False即可,此时存入json的中文即可正常显示。)
39 If check_circular is false, then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse).
40 If allow_nan is false, then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (NaN, Infinity, -Infinity).
41 indent:应该是一个非负的整型,如果是0就是顶格分行显示,如果为空就是一行最紧凑显示,否则会换行且按照indent的数值显示前面的空白分行显示,这样打印出来的json数据也叫pretty-printed json
42 separators:分隔符,实际上是(item_separator, dict_separator)的一个元组,默认的就是(‘,’,’:’);这表示dictionary内keys之间用“,”隔开,而KEY和value之间用“:”隔开。
43 default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError.
44 sort_keys:将数据根据keys的值进行排序。
45 To use a custom JSONEncoder subclass (e.g. one that overrides the .default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.
46 '''
json
pickle
所有的python中的数据类型都可以转化成字符串形式
pickle序列化的内容只有python能理解
且部分反序列化依赖python代码

shelve
序列化句柄
使用句柄直接操作,非常方便
类似于字典操
是基于pickle的封装

1 import shelve
2 
3 db = shelve.open('shelveDict', writeback=True)  # 打开一个文件 writeback,可以修改内容
4 db['wangzhe'] = '233'  # 向文件中添加内容,添加方式与给字典添加键值对相同
5 db.close()  # 关闭文件
6 
7 db = shelve.open('shelveDict')  # 打开文件
8 print(db['wangzhe'])  # 向从字典中获取键的方式一样读取内容
9 db.close()  # 关闭文件
shelve

 

posted @ 2018-09-28 23:25  写bug的日子  阅读(125)  评论(0编辑  收藏  举报