What is serialization?
Serialization is the ability to convert the data type in memory into a string so that it can be stored on the hard disk or transferred to the remote in the network, because the hard disk and the network transmit only receive bytes
Two modules for serialization
1. JSON for conversions between string and Python data types
2. Pickle for conversion between Python-specific data types and Python data types
The JSON module provides 4 functions: dumps, dump, loads, and load can be cross-platform
The Pickle module provides 4 functions: dumps, dump, loads, and load can only be used in Python
JSON usage
ImportJsondata= { 'role':'Alex', ' Life': 50}#JSON serializationJson_str =json.dumps (data)Print(Json_str,type (JSON_STR))#Output#{"Role": "Alex", "Life": <class ' str ' >#JSON deserializationdata =json.loads (JSON_STR)Print(Data,type (data))#Output#{' role ': ' Alex ', ' life ': <class ' dict ' >
JSON usage of mate file operations
#serialization of mate file operationsWith open ('./tmp/json.pk','W') as Fp:json.dump (DATA,FP)#deserialization of a mate file operationWith open ('tmp/json.pk') as Fp:data=json.load (FP)Print(Data,type (data))#Output#{' Life ': ' Role ': ' Alex '} <class ' Dict ' >
Pickle usage
ImportPickle#Serialization of PicklePickle_str =pickle.dumps (data)Print(Pickle_str,type (PICKLE_STR))#Output#B ' \x80\x03}q\x00 (X\x04\x00\x00\x00lifeq\x01k2x\x04\x00\x00\x00roleq\x02x\x04\x00\x00\x00alexq\x03u < Class ' bytes ' >#Pickle Deserializationdata =pickle.loads (PICKLE_STR)Print(Data,type (data))#Output#{' Life ': ' Role ': ' Alex '} <class ' Dict ' >
Combine file operations
# Pickle serialization with open ('tmp/pickle.pk','wb' ) combined with file manipulation As fp: pickle.dump (DATA,FP)# Pickle deserialization with open (' tmp/') combined with the file operation pickle.pk','rb') as fp: = pickle.load (FP) Print(data,type (data))
Note: Pickle serialization is not a string, but a byte, so in the file operation, you need to be aware of the use of ' WB ' and ' RB '
20180209-json&pickle Module