and pickle deserialization json
First, the definition
Serialization: converting the non-persistent memory and easy to transfer persistent objects and object transmission process.
Deserialize: persistent and will be transmitted to non-persistent object into the object and the transmission process.
Second, the application scenarios
Cross-platform data transmission;
changes to the object when the program remain on the run
Third, functions and modules
1. json
dumps (), dump () (serialization)
loads (), load () (deserialization)
2. pickle
dumps (), dump () (serialization)
loads (), load () (deserialization)
Fourth, the case
序列化 info={"name":"kezi","age":22} f=open("test.text","w") f.write(str(info)) f.close() 反序列 info={"name":"kezi","age":22} f=open("test.text","r") data=eval(f.read()) f.close() print (data['age']) 打印结果 22 json 简单用法 import json info={"name":"kezi","age":22} f=open("test.text","w") print(json.dumps(info)) f.write(json.dumps(info)) #f.write(str(info)) f.close() 打印结果 {"age": 22, "name": "kezi"} import json f=open("test.text","r") #data=eval(f.read()) data=json.loads(f.read()) f.close() print (data['age']) 打印结果 22 序列化 pickle import pickle def si(name): print("helle",name) info={"name":"kezi","age":22,"func":si} f=open("test.text","wb") print(pickle.dumps(info)) f.write(pickle.dumps(info)) #f.write(str(info)) f.close() 打印结果 b'\x80\x03}q\x00(X\x04\x00\x00\x00nameq\x01X\x04\x00\x00\x00keziq\x02X\x03\x00\x00\x00ageq\x03K\x16X\x04\x00\x00\x00funcq\x04c__main__\nsi\nq\x05u.'Si (name): DEFthe pickle Import Deserialization print("helle2",name) f=open("test.text","rb") #data=eval(f.read()) data=pickle.loads(f.read()) f.close() print (data["func"]("kezi")) 打印结果 helle2 kezi None 另一种简化写法 import pickle def si(name): print("helle",name) info={"name":"kezi","age":22,"func":si} f=open("test.text","wb") pickle.dump(info,f) #f.write(pickle.dumps(info)) f.close() import pickle def si(name): print("helle2",name) f=open("test.text","rb") #data=eval(f.read()) data=pickle.load(f)#data=pickle.loads(f.read()) f.close() print (data ["func"]("kezi"))
pickle type sequence of bites result, only suitable for interaction between the Python machine.
JSON type
|
Python type
|
{}
|
dict
|
[]
|
list
|
"string"
|
'Str' or u'unicode '
|
1234.56
|
int or float
|
true/false
|
True/False
|
null
|
None
|
Note:
(1) serialized and deserialized in order to solve the transmission problem of persistent objects in memory;