json 序列化和反序列化
1 import json 2 3 info ={ 4 'age':22, 5 'name':'Ri' 6 } 7 8 with open('test.txt','w',encoding = 'utf-8') as f: 9 print(type(json.dumps(info))) 10 f.write(json.dumps(info)) 11 12 #<class 'str'>
(使用str强制转换dict,反序列化时使用eval,可返回字典,不常用,不用记)
1 import json 2 3 with open('test.txt','r',encoding = 'utf-8') as f: 4 data =json.loads(f.read()) 5 6 print(data) 7 print(type(data)) 8 # ============================================================================= 9 # {'age': 22, 'name': 'Ri'} 10 # <class 'dict'> 11 # =============================================================================
1 import json 2 3 def func(name): 4 print('hello,',name) 5 6 info ={ 7 'age':22, 8 'sex':'m', 9 'func':func 10 } 11 12 f = open('test.txt','w',encoding = 'utf-8') 13 14 f.write(json.dumps(info)) 15 f.close() 16 17 # ============================================================================= 18 # TypeError: Object of type 'function' is not JSON serializable 19 # =============================================================================
json 只能处理简单的数据类型,比如字典,列表。因为json主要负责不同语言间的交互。是所有语言通用的
但是不同语言间的类以及特性,库存在很多差别,所以json只支持最简单的
xml 正在逐渐的被json、取代。xml的作用与json的相同,但json的使用更加简单。至今很多传统的公司还在
使用的接口还是xml
pickle 可以处理python所有的数据类型
1 import pickle 2 3 def func(name): 4 print('hello,',name) 5 6 info ={ 7 'age':22, 8 'sex':'m', 9 'func':func 10 } 11 12 f = open('test.txt','wb') 13 14 print(pickle.dumps(info)) 15 f.write(pickle.dumps(info)) 16 f.close() 17 18 19 #b'x80x03}qx00(Xx03x00x00x00ageqx01Kx16Xx03x00x00 20 #x00sexqx02Xx01x00x00x00mqx03Xx04x00x00x00funcq 21 #x04c__main__ func qx05u.'
1 import pickle 2 3 f = open('test.txt','rb') 4 5 data = pickle.loads(f.read()) 6 7 print(data) 8 9 #runfile('C:/Users/Administrator/Ri/day5/Json.py', wdir='C:/Users/Administrator/Ri/day5') 10 #b'x80x03}qx00(Xx03x00x00x00ageqx01Kx16Xx03x00x00x00sexqx02Xx01x00x00x00mqx03Xx04x00x00x00funcqx04c__main__ func qx05u.' 11 # 12 #runfile('C:/Users/Administrator/Ri/day5/json1.py', wdir='C:/Users/Administrator/Ri/day5') 13 #{'age': 22, 'sex': 'm', 'func': <function func at 0x00000000098D19D8>} 14 # 15 #data['func']('World') 16 #hello, World
可能是使用的编辑器的原因,序列化后程序结束,函数func 被释放,所以在反序列化是的添加函数。并且函数
名如果一样,函数体不一样,会执行反序列化的函数
pickle只有在python的本语言才能使用
1 import pickle 2 3 def func(name): 4 print('hello,',name) 5 6 info ={ 7 'age':22, 8 'sex':'m', 9 'func':func 10 } 11 12 f = open('test.txt','wb') 13 14 pickle.dump(info,f) #f.write(pickle.dumps(info)) 15 f.close()
1 import pickle 2 3 def func(name): 4 print('hello3141,',name) 5 6 7 f = open('test.txt','rb') 8 9 data = pickle.load(f) #data = pickle.loads(f.read()) 10 11 print(data['func']('world2018!')) 12 13 f.close() 14 15 #hello3141, world2018! 16 #None
只能dump或者load一次
import json def func(name): print('hello,',name) info ={ 'age':22, 'sex':'m', #'func':func } f = open('test.txt','w') info['age'] = 12 f.write(json.dumps(info)) # 每次dump 会把之前的状态对冲掉 f.close()
import json f = open('test.txt','r') data = json.loads(f.read()) # 只能locd一次 print(data['age']) # #12