JSON & Pickle Modules
Two modules for serialization
- JSON, used to convert between string and Python data types
- Pickle for conversion between Python-specific types and Python data types
The JSON module provides four functions: dumps, dump, loads, load
The Pickle module provides four functions: dumps, dump, loads, load
#JSON can only handle simple data types that interact with other languages#JSON different platform data processing to interact#storing data and reading data with JSON implementations#serialization of data storedinfo = { 'name':'python', ' Age': 30}Importjsonf= Open ("Test",'W')#F.write (str (info)) #str变为字符串F.write (Json.dumps (info))#deserialization of reading dataImportjsonf= Open ("Test",'R') Data=json.loads (F.read ())Print(data[" Age"])#Pickle processing complex can serialize all data types#Serialization ofImportPickledefSaihi (name):Print("Hello", name) info= { 'name':'python', ' Age': 30, 'func': Saihi}f= Open ("Test",'WB')#F.write (str (info)) #str变为字符串F.write (Pickle.dumps (info))#deserializationImportPickledefSaihi (name):Print("Hello", name)Print("Hello1", name) F= Open ("Test",'RB') Data=pickle.loads (F.read ())Print(data["func"]("python"))#Pickle Dump works the same as dumpsImportPickledefSaihi (name):Print("Hello", name) info= { 'name':'python', ' Age': 30, 'func': Saihi}f= Open ("Test",'WB') Pickle.dump (info,f) f.close ()#Load in pickleImportPickledefSaihi (name):Print("Hello", name)Print("Hello1", name) F= Open ("Test",'RB') Data=pickle.load (f)#serialization with JSON dump two timesImportJsoninfo= { 'name':'python', ' Age': 30,}f= Open ("Test",'W') F.write (Json.dumps (info)) info[' Age'] = 22F.write (Json.dumps (info)) F.close ()#Note: Dump one load at a time as a snapshot in a virtual machine
Python--json and Pickle serialization