(1)python提供了pickle模块实现序列化
import pickle
d=dict(name='Bob',age=30,score=98)
pickle.dumps(d) # 把任意对象序列化为一个bytes
f=open('dump.txt','wb') # 以二进制写模式打开
pickle.dump(d,f)
f.close()
f=open('dump.txt','rb')
pickle.load(f)
f.close()
(2)JSON
JSON类型 Python类型
{} dict
[] list
"string" str
1234.56 int或float
true/false True/False
null None
import json
d=dict(name='Bob',age=30,score=88)
json.dumps(d)
json_str='{"age":20,"score":88,"name":"bob"}'
json.loads(json_str)
import json
class Student(object):
def __init__(self,name,age,score):
self.name=name
self.age=age
self.score=score
def student2dict(std):
return {
'name':std.name,
'age':std.age,
'acore':std.score
}
s=Student('bob',20,99)
print(json.dumps(s,default=student2dict))
print(json.dumps(s,default=lambda obj:obj.__dict__)) # class的实例都有一个__dict__属性,他就是一个dict
def dict2student(d):
return Student(d['name'],d['age'],d['score'])
json_str='{"age":20,"score":88,"name":"bob"}'
print(json.loads(json_str,object_hook=dict2student))