#pickling import pickle,json # d = dict(name='傻狗1',age=300,score=100) # d1 = pickle.dumps(d)#pickle.dumps()方法把任意對象序列化成一個bytes,而後,就能夠把這個bytes寫入文件 # print(d1)#b'\x80\x03}q\x00(X\x04\x00\x00\x00nameq\x01X\x07\x00\x00\x00\xe5\x82\xbb\xe7\x8b\x971q\x02X\x03\x00\x00\x00ageq\x03M,\x01X\x05\x00\x00\x00scoreq\x04Kdu.' # with open('./dump.txt','wb') as f: # pickle.dump(d,f)#用另外一個方法pickle.dump()直接把對象序列化後寫入一個file-like Object # with open('./dump.txt','rb') as f: # d = pickle.load(f)#用pickle.load()方法從一個file-like Object中直接反序列化出對象 # print(d)#{'name': '傻狗1', 'age': 300, 'score': 100} #JSON #python對象轉JSON # dict1 = dict(name='傻狗1',age=300,sorce=100) # json1 = json.dumps(dict1)#dumps()方法返回一個str,內容就是標準的JSON # print(json1)#{"name": "\u50bb\u72d71", "age": 300, "sorce": 100} # with open('./dump1.json','w') as f:#dump()方法能夠直接把JSON寫入一個file-like Object # json2 = json.dump(dict1,f) #JSON轉python對象 # json3 = '{"age": 20, "score": 88, "name": "Bob"}' # dict2 = json.loads(json3)#{'age': 20, 'score': 88, 'name': 'Bob'} loads()把JSON反序列化爲Python對象 # print(dict2) #with open('./dump1.json','r') as f1: # dict3 = json.load(f1)#load()從file-like Object中讀取字符串並反序列化 # print(dict3)#{'name': '傻狗1', 'age': 300, 'sorce': 100} #因爲JSON標準規定JSON編碼是UTF-8,因此咱們老是能正確地在Python的str與JSON的字符串之間轉換 #class實例對象轉JSON class Point(object): def __init__(self,name,age,sorce): self.name = name self.age = age self.sorce = sorce p1 = Point('傻狗2',300,100) json4 = json.dumps(p1,ensure_ascii=False,default=lambda obj : obj.__dict__)#json.dumps 序列化時對中文默認使用的ascii編碼.想輸出真正的中文須要指定ensure_ascii=False # print(p1.__dict__)#{'name': '傻狗2', 'age': 300, 'sorce': 100} class的實例都有一個__dict__屬性,它就是一個dict,用來存儲實例變量。也有少數例外,好比定義了__slots__的class print(json4)#{"name": "\u50bb\u72d72", "age": 300, "sorce": 100} Point實例首先被匿名函數轉換成dict,而後再被順利序列化爲JSON #JSON轉class實例對象 json5 = '{"age": 20, "score": 88, "name": "Bob"}' p2 = json.loads(json5,object_hook=lambda obj : Point(obj['name'],obj['age'],obj['score'])) print(p2)#<__main__.Point object at 0x000001AFE1A382E8> loads()方法首先轉換出一個dict對象,而後,咱們傳入的object_hook函數負責把dict轉換爲Student實例