Python的序列化和反序列化
不同的程式語言有不同的資料型別; 比如說:
Python的資料型別有(dict、list、string、int、float、long、bool、None)
Java的資料型別有(bool、char、byte、short、int、long、float、double)
C的資料型別有(bit、bool、char、int、short、long、unsigned、double、float)
Tcl的資料型別(int、bool、float、string)
Ruby的資料型別(Number、String、Ranges、Symbols、true、false、Array、Hash)
...
他們的共同特點是,都有字串型別!
所以要實現不同的程式語言之間物件的傳遞,就必須把物件序列化為標準格式,比如XML,但更好的方法是序列化為JSON,因為JSON表示出來就是一個字串,可以被所有語言讀取,也可以方便地儲存到磁碟或者通過網路傳輸。
JSON不僅是標準格式,並且比XML更快,而且可以直接在Web頁面中讀取,非常方便.
JSON型別 Python型別 {} dict [] list "string" str 1234.56 int或float true True false False null None |
在python中,
序列化可以理解為:把python的物件編碼轉換為json格式的字串;
反序列化可以理解為:把json格式字串解碼為python資料物件。
在python的標準庫中,專門提供了json庫與pickle庫來處理這部分。
json的dumps方法和loads方法,可實現資料的序列化和反序列化。具體來說,
dumps方法,可將json格式資料序列為Python的相關的資料型別;
loads方法則是相反,把python資料型別轉換為json相應的資料型別格式要求。
在序列化時,中文漢字總是被轉換為unicode碼,在dumps函式中新增引數ensure_ascii=False即可解決!!!
1、Json序列化如下:
1 import json 2 print (json.__all__) #檢視json庫的所有方法 3 ['dump', 'dumps', 'load', 'loads', 'JSONDecoder', 'JSONEncoder']
未在dumps函式中新增引數ensure_ascii=False,結果如下:
1 #coding: utf-8 2 import json 3 dict = {'name':'zhangsan', 'age':33, 'address':'紅星路'} 4 print('未序列化前的資料型別為:', type(dict)) 5 print('未序列化前的資料:', dict) 6 #對dict進行序列化的處理 7 dict_xu = json.dumps(dict) #直接進行序列化 8 print('序列化後的資料型別為:', type(dict_xu)) 9 print('序列化後的資料為:', dict_xu)
未序列化前的資料型別為: <class 'dict'> 未序列化前的資料: {'name': 'zhangsan', 'address': '紅星路', 'age': 33} 序列化後的資料型別為: <class 'str'> 序列化後的資料為: {"name": "zhangsan", "address": "\u7ea2\u661f\u8def", "age": 33}
在dumps函式中新增引數ensure_ascii=False,結果如下:
1 #coding: utf-8 2 import json 3 4 dict = {'name':'zhangsan', 'age':33, 'address':'紅星路'} 5 print('未序列化前的資料型別為:', type(dict)) 6 print('為序列化前的資料:', dict) 7 #對dict進行序列化的處理 8 dict_xu = json.dumps(dict,ensure_ascii=False) #新增ensure_ascii=False進行序列化 9 print('序列化後的資料型別為:', type(dict_xu)) 10 print('序列化後的資料為:', dict_xu)
輸出:
未序列化前的資料型別為: <class 'dict'> 為序列化前的資料: {'address': '紅星路', 'age': 33, 'name': 'zhangsan'} 序列化後的資料型別為: <class 'str'> 序列化後的資料為: {"address": "紅星路", "age": 33, "name": "zhangsan"}
2、Json反序列化如下:
1 #coding: utf-8 2 import json 3 dict = {'name':'zhangsan', 'age':33, 'address':'紅星路'} 4 print('未序列化前的資料型別為:', type(dict)) 5 print('未序列化前的資料:', dict) 6 #對dict進行序列化的處理 7 dict_xu = json.dumps(dict,ensure_ascii=False) #新增ensure_ascii=False進行序列化 8 print('序列化後的資料型別為:', type(dict_xu)) 9 print('序列化後的資料為:', dict_xu) 10 #對dict_xu進行反序列化處理 11 dict_fan = json.loads(dict_xu) 12 print('反序列化後的資料型別為:', type(dict_fan)) 13 print('反序列化後的資料為: ', dict_fan)
輸出:
未序列化前的資料型別為: <class 'dict'> 未序列化前的資料: {'name': 'zhangsan', 'age': 33, 'address': '紅星路'} 序列化後的資料型別為: <class 'str'> 序列化後的資料為: {"name": "zhangsan", "age": 33, "address": "紅星路"} 反序列化後的資料型別為: <class 'dict'> 反序列化後的資料為: {'name': 'zhangsan', 'age': 33, 'address': '紅星路'}
在實際的工作中,序列化或者反序列化的可能是一個檔案的形式,不可能像如上寫的那樣簡單的。
下來就來實現這部分,把檔案內容進行序列化和反序列化;
一、先來看序列化的程式碼,兩步操作:1、先序列化 列表物件 ;2、把序列化成的字串寫入檔案:
1 #coding: utf-8 2 import json 3 4 list = ['Apple','Huawei','selenium','java','python'] 5 #把list先序列化,寫入到一個檔案中 6 #兩步操作 1步先序列化 列表物件 2步把序列化成的字串寫入檔案 7 json.dump(list, open('e:/test.txt','w')) 8 r1=open('e:/test.txt','r') 9 print(r1.read())
輸出:
["Apple", "Huawei", "selenium", "java", "python"]
二、反序列化,兩步操作:1、先讀取檔案的字串物件;2、然後反序列化成列表物件:
1 #coding: utf-8 2 import json 3 4 list = ['Apple','Huawei','selenium','java','python'] 5 #把list先序列化,寫入到一個檔案中 6 #兩步操作 1步先序列化 列表物件 2步把序列化成的字串寫入檔案 7 json.dump(list, open('e:/test.txt','w')) 8 r1=open('e:/test.txt','r') 9 print(r1.read()) 10 #------------------------------------------------------------ 11 #兩步操作:1、先讀取檔案的字串物件;2、然後反序列化成列表物件 12 res=json.load(open('e:/test.txt','r')) 13 print (res) 14 print('資料型別:',type(res))
輸出:
["Apple", "Huawei", "selenium", "java", "python"] ['Apple', 'Huawei', 'selenium', 'java', 'python'] 資料型別: <class 'list'>