json 普通的字典形式
pickle 复杂的
还有dumps loads, dump load成对出现
test.text
{"name": "alex", "age": 22}
一、序列化
#import json
import pickle
def sayhi(name):
print("hello,",name)
info = {
'name':'alex',
'age':22,
'func':sayhi
}
f = open("test.text","wb")
#print(json.dumps(info))
print( )
f.write( pickle.dumps( info) )
f.close()
反序列化
import pickle
def sayhi(name):
print("hello2,",name)
f = open("test.text","rb")
data = pickle.loads(f.read())
print(data["func"]("Alex"))
结果
test.text
�}q
hello2, Alex
None
二、
#import json
import pickle
def sayhi(name):
print("hello,",name)
info = {
'name':'alex',
'age':22,
'func':sayhi
}
f = open("test.text","wb")
pickle.dump(info,f) #f.write( pickle.dumps( info) )
f.close()
反序列化
import pickle
def sayhi(name):
print("hello2,",name)
f = open("test.text","rb")
data = pickle.load(f) #data = pickle.loads(f.read())
print(data["func"]("Alex"))
结果:
hello2, Alex
None
三、
import json
def sayhi(name):
print("hello,",name)
info = {
'name':'alex',
'age':22,
#'func':sayhi
}
f = open("test.text","w")
f.write( json.dumps( info) )
info['age'] = 21
f.write( json.dumps( info) )
f.close()
反序列化
import json
f = open("test.text","r")
#data = json.loads(f.read()) #data = pickle.loads(f.read())
for line in f:
print(json.loads(line))
结果:
报错
File "C:\Program Files\Python36-32\lib\json\decoder.py", line 342, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 28 (char 27)
只dumps一次,只loads一次