one. JSON moduleSerialization: Changing the shape of an object so that he can be stored in a file or transmitted over a network, serialization is called persistence, which is to store objects in permanent media, so that they are not lost due to power loss. JSON (JavaScript Object Notation) is a lightweight data interchange format, JSON is used to convert strings and Python data types, and the JSON module provides four functions: dumps, dump, loads, load
examples of json.dumps and json.loads:
1 #!/usr/bin/python32 ImportJSON3data = {'name':'Jiesen','Height': 175,'Weight':'68KG'}4 #dumps to String5Json_str =json.dumps (data)6 Print('dumps to string:', Json_str,'Type:', type (JSON_STR))7 #loads back .8Json_dict =json.loads (JSON_STR)9 Print('loads back:', Json_dict,'Type:', type (json_dict))
Output: Dumps to string: {"name": "Jiesen", "height": 175, "Weight": "68KG"} Type: <class ' str ' >loads back: {' name ': ' Jiesen ', ' Heig HT ': 175, ' weight ': ' 68KG ' type: <class ' dict ' >
If you are working with files instead of strings, you can encode and decode them using Json.dump and json.load. For example:
1 #!/usr/bin/python32 ImportJSON3With open ('Data_json.txt','w+', encoding='Utf-8') as F:4 json.dump (data,f)5With open ('Data_json.txt','R') as F:6Data_r =json.load (f)7 Print(Data_r)
Output: {' name ': ' Jiesen ', ' height ': 175, ' weight ': ' 68KG '}
two. Pickle ModuleThe pickle serialized object is a binary byte that saves a file store to a file or is transmitted over the network.
examples of pickle.dump and pickle.load:
1 #!/use/bin/python32 ImportPickle3data = {'K1': 1,'K2': 2}4 #open a file in binary mode and save the data dump to the file5With open ('Pickle_data.txt','WB') as F:6 pickle.dump (data,f)7 #opens the file in binary read mode and loads the load8With open ('Pickle_data.txt','RB') as F:9FB =pickle.load (f)Ten Print(FB)
Output:
{' K1 ': 1, ' K2 ': 2}
If you are not working with files, you can use Pickle.dumps and pickle.loads, for example:
data = {'name':'Jiesen','Height': 175,'Weight':'68KG'}#convert to a byte stream objectPickle_byte =pickle.dumps (data)Print(Pickle_byte,'format:', type (pickle_byte))#recovering an object from a byte streamPickle_dict =pickle.loads (pickle_byte)Print(Pickle_dict,'format:', type (pickle_dict))
Output:
B ' \x80\x03}q\x00 (x\x04\x00\x00\x00nameq\x01x\x06\x00\x00\x00jiesenq\x02x\x06\x00\x00\x00heightq\x03k\xafx\x06\ x00\x00\x00weightq\x04x\x04\x00\x00\x0068kgq\x05u. ' Format: <class ' bytes ' >
{' name ': ' Jiesen ', ' height ': 175, ' weight ': ' 68KG ' format: <class ' Dict ' >
Summarize:
1.pickle serializes bytes, while JSON serializes characters.
2.json.dump,json.load and Pickle.dump,pickle.road are dealing with files.
Serialization of Days-json and Pickle