Serialization module
Purpose of serialization
1. Persist the custom object in some form of storage;2. Transfer objects from one place to another. 3, make the program more maintenance. 1.json
The JSON module provides four functions: dumps, dump, loads, load
ImportJSON #(1) Dumps DIC = {'K1':'value 1','K2':'Value 2','K3':'Value 3'}str_dic= Json.dumps (DIC)#Convert a dictionary to a stringPrint(Type (str_dic), str_dic)" "Result: <class ' str ' > {"K3": "\u503c3", "K1": "\u503c1", "K2": "\u503c2"}" " #(2) loads Dic2 = Json.loads (str_dic)#convert a serialization to a dictionaryPrint(Type (DIC2), Dic2)" "Result: <class ' dict ' > {' K3 ': ' Value 3 ', ' K1 ': ' Value 1 ', ' K2 ': ' Value 2 '}" " #(3) Dump F1 = open ('Json_file','W')#the default encoding method is GBKDIC = {'K1':'value 1','K2':'Value 2','K3':'Value 3'}json.dump (DIC,F1)#The Dump method converts the DIC dictionary information into a JSON string to write to the filef1.close () #(4) Load f = open ('Json_file')#the default encoding method is GBKDic2 = Json.load (f)#The Load method converts the contents of a file into a data type returnedf.close ()Print(Type (DIC2), Dic2)" "Result: <class ' dict ' > {' K3 ': ' Value 3 ', ' K1 ': ' Value 1 ', ' K2 ': ' Value 2 '}" " #(5) ensure_ascii Importjsonf= Open ('file','W')#open a file in a written way #默认编码方式是GBKJson.dump ({'Nationality':'China'},F)#Convert {' Nationality ': ' China '} to a JSON string to write to the fileret = Json.dumps ({'Nationality':'China'})#Convert {' Nationality ': ' China '} to a JSON string to assign to the variable retF.write (ret+'\ n')#writes the JSON string contents of RET to a fileJson.dump ({'Nationality':'United States'},f,ensure_ascii=false)#dump for Chinese default ASCII code, if not used to specify Ensure_ascii=falseret = Json.dumps ({'Nationality':'United States'},ensure_ascii=false)#dumps for Chinese default to ASCII code, if you do not use to specify Ensure_ascii=falseF.write (ret+'\ n') F.close () #(6) Other parameter description R" "Serialize obj to a JSON formatted str. (string representation of the JSON object) Skipkeys: The default value is False if the data in the Dict keys is not the basic type of Python (Str,unicode,int, Long,float,bool,none), when set to False, the TypeError error is reported.
When set to true, this type of key ensure_ascii is skipped: when it is true, all non-ASCII characters are displayed as \uxxxx sequences, just set the ENSURE_ASCII to false at dump. In this case, the Chinese in JSON can be displayed normally. If Check_circular is false, then the circular reference check for container types would be skipped and a circular referen Ce would result in
An overflowerror (or worse). If Allow_nan is false and then it'll be a valueerror to serialize out of range float values (Nan, INF,-inf) in strict comp Liance of the
JSON specification, instead of using the JavaScript equivalents (NaN, Infinity,-infinity). Indent: Should be a non-negative integer, if it is 0 is the Shelf branch display, if empty is the most compact display, otherwise will be wrapped and according to the value of indent display the previous blank branch display, so the printed JSON data is also called
pretty-printed JSON separators: delimiter, actually (Item_separator, dict_separator) a tuple, the default is (', ', ': '), this means that the dictionary within the keys with "," separated by "and" between Key and value ":
Separated The default (obj) is a function, that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. Sort_keys: Sorts the data according to the value of keys. To use a custom Jsonencoder subclass (e.g. one, overrides the. Default () method to serialize additional types), Specif Y it with the
CLS Kwarg; Otherwise jsonencoder is used." " #(7) formatted output ImportJsondata= {'username':['Li Hua','Erlengzi'],'Sex':'male',' Age': 16}json_dic2= Json.dumps (data,sort_keys=true,indent=2,separators= (',',':'), ensure_ascii=False)Print(JSON_DIC2)" "Result: {"age": +, "sex": "Male", "username": ["Li Hua", "Erlengzi"]}" "
2.pickle
The difference between JSON and pickle
Two module JSON for serialization, for converting between string and Python data types pickle, for conversion between Python-specific types and Python data types Pickle module provides four functions: dumps, dump (serialization, Save), Loads (deserialization, read), load (can not only serialize dictionary, list ...) Can serialize arbitrary data types in Python)
ImportPickle #(1) Dumps DIC = {'K1':'v1','K2':'v2','K3':'v3'}str_dic= Pickle.dumps (DIC)#Dumps method converts a dictionary into bytesPrint(str_dic)" "results: B ' \x80\x03}q\x00 (x\x02\x00\x00\x00k2q\x01x\x02\x00\x00\x00v2q\x02x\x02\x00\x00\x00k1q\x03x\x02\x00\x00 \x00v1q\x04x\x02\x00\x00\x00k3q\x05x\x02\x00\x00\x00v3q\x06u. '" " #(2) loads Dic2 = Pickle.loads (str_dic)#loads deserialization method to convert dumps-generated bytes into data typesPrint(DIC2)#Dictionary" "result: {' K2 ': ' v2 ', ' K1 ': ' v1 ', ' K3 ': ' V3 '}" " #(3) Dump ImportTimestruct_time= Time.localtime (1000000000)Print(struct_time) F= Open ('Pickle_file','WB') Pickle.dump (struct_time,f)#dump serialization method to convert content to serialized data to a file summaryf.close () #(4) Load f = open ('Pickle_file','RB') struct_time2= Pickle.load (f)#load deserialization method to read serialized data from a filePrint(struct_time2.tm_year)
3.shelve
#shelve is also a serialization tool provided to us by Python, which is simpler to use than pickle. #shelve only provides us with an open method, which is accessed using key and is similar to a dictionary. #(1) Shelve deposit data ImportSHELVEF= Shelve.open ('Shelve_file') f['Key'] = {'int': 10,'float': 9.5,'string':'Sample Data'}#directly to the file handle, you can deposit dataf.close () #(2) shelve read out data ImportSHELVEF1= Shelve.open ('Shelve_file') Existing= f1['Key']#when you take out the data, you just need to get it directly with key, but if key doesn't exist, it will be an error.f1.close ()Print(existing)
Python3 Serialization Module (JSON, Pickle, shelve)