Skip to content

Commit e1f067c

Browse files
authored
练习序列化和反序列化
1 parent 6070b23 commit e1f067c

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

test31.py

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
'练习序列化和反序列化'
5+
6+
__author__ = 'sergiojune'
7+
import pickle
8+
import json
9+
d = {'name': 'bob', 'age': 20, 'score': 80}
10+
# 序列化,这个是序列化成bytes
11+
p = pickle.dumps(d)
12+
print(p)
13+
# 这个序列化后直接存在指定文件
14+
with open('pickle.txt', 'wb') as f:
15+
pickle.dump(d, f)
16+
17+
# 反序列化
18+
# 这个是将bytes反序列化
19+
p = pickle.loads(p)
20+
print(p)
21+
# 这个是将文件反序列化
22+
with open('pickle.txt', 'rb') as f:
23+
d = pickle.load(f)
24+
print(d)
25+
26+
27+
# 若要在个语言之间相互传递对象,这时就需要序列化成JSON或XML等格式
28+
# 这里序列化成JSON,用的是json库
29+
d = {'name': 'bart', 'age': 22, 'score': 76}
30+
j = json.dumps(d)
31+
print(j)
32+
# 序列化后写入文件
33+
with open('json.txt', 'w') as f:
34+
json.dump(d, f)
35+
# 反序列化
36+
f = json.loads(j)
37+
print(f)
38+
# 从文件中反序列化
39+
with open('json.txt', 'r') as f:
40+
w = json.load(f)
41+
print('文件:', w)
42+
43+
44+
# 序列化自定义类
45+
class Student(object):
46+
def __init__(self, name, age, score):
47+
self.name = name
48+
self. age = age
49+
self.score = score
50+
51+
52+
s = Student('tom', 23, 68)
53+
# 这个是获取对象的字典形式
54+
print(s.__dict__)
55+
# 直接序列化会出错,抛TypeError: Object of type 'Student' is not JSON serializable,说该对象不可序列化
56+
# o = json.dumps(s)
57+
# 对自定义对象序列化需要自己先将对象转换成字典才能序列化
58+
59+
60+
# 将student转换成字典
61+
def student2dict(obj):
62+
return {'name': obj.name,
63+
'age': obj.age,
64+
'score': obj.score}
65+
66+
67+
# 现在序列化
68+
o = json.dumps(s, default=student2dict)
69+
print(o)
70+
# 可以利用类的特性和匿名函数一行代码进行序列化
71+
o1 = json.dumps(s, default=lambda obj: obj.__dict__)
72+
print('简易序列化', o1)
73+
74+
# 反序列化
75+
76+
77+
# 在自定义类中,同样也需要加个函数将序列化后的字典转换成对象的对象
78+
def dict2student(d):
79+
return Student(d['name'], d['age'], d['score'])
80+
81+
82+
fan = json.loads(o, object_hook=dict2student)
83+
# 这样就获取到student对象
84+
print(fan)
85+
86+
87+
# 作业:对中文进行JSON序列化时,json.dumps()提供了一个ensure_ascii参数,观察该参数对结果的影响
88+
obj = dict(name='小明', age=20)
89+
# 当ensure_ascii为True,会对中文进行编码
90+
s = json.dumps(obj, ensure_ascii=True)
91+
print(s)
92+
# 当ensure_ascii为False,不会对中文进行编码
93+
s = json.dumps(obj, ensure_ascii=False)
94+
print(s)

0 commit comments

Comments
 (0)