python------Json与pickle数据序列化

时间:2022-03-17 16:33:57

一.json序列化

xml在被json取代,不同平台之间的语言转换,只能处理简单的。复杂的用pickle;

pickle只能在python中用,而在Java中json也可以被识别。

info = {
'name':'xiaolaizi',
'age':22
}
f = open("test.text","w")
f.write(str(info))
------------------------------------------------
import json
info = {
'name':'xiaolaizi',
'age':22
}
f = open("test.text","w")
f.write(json.dumps(info))
---------------------------------------
import pickle
info = {
'name':'xiaomaizi',
'age':22
}
f = open("test.text","wb")
f.write(pickle.dumps(info))
#等价pickle.dump(info,f)
 
 
f = open("test.text","r")
data = eval(f.read())
f.close()
print(data['age']) #反序列化
-------------------------------------------
import json
f = open("test.text","r")
data = json.loads(f.read())
f.close()
print(data['age']) --------------------------------------------
import pickle
f = open("test.text","rb")
data = pickle.loads(f.read())
#data = pickle.loads(f)
f.close()
print(data['age'])