1 import json 3 dic={'name':'alvin','age':23,'sex':'male'}
4 print(type(dic))#<class 'dict'> 6 j=json.dumps(dic)
7 print(type(j))#<class 'str'> 10 f=open('序列化对象','w')
11 f.write(j) #-------------------等价于json.dump(dic,f)
12 f.close()
13 #-----------------------------反序列化<br>
14 import json
15 f=open('序列化对象')
16 data=json.loads(f.read())# 等价于data=json.load(f)
1 import pickle 3 dic={'name':'alvin','age':23,'sex':'male'} 5 print(type(dic))#<class 'dict'> 7 j=pickle.dumps(dic)
8 print(type(j))#<class 'bytes'> 11 f=open('序列化对象_pickle','wb')#注意是w是写入str,wb是写入bytes,j是'bytes'
12 f.write(j) #-------------------等价于pickle.dump(dic,f) 14 f.close()
15 #-------------------------反序列化
16 import pickle
17 f=open('序列化对象_pickle','rb') 19 data=pickle.loads(f.read())# 等价于data=pickle.load(f) 22 print(data['age']