How to understand serialized pickle and json modules
This article will explain in detail how to understand the serialization of pickle and json modules, the content of the article is of high quality, so the editor will share it with you for reference. I hope you will have some understanding of the relevant knowledge after reading this article.
Two modules for serialization
Json: used for converting between string and Python data types
Pickle: used to convert between python-specific types and python data types
Json provides four functions: dumps, dump, loads, load
Pickle provides four functions: dumps, dump, loads, load
Import pickledata = ['aa',' bb', 'cc'] # convert to sequence data p_str = pickle.dumps (data) print (p_str) # convert from sequence to data inverse_data = pickle.loads (p_str) print (inverse_data) # convert to sequence and write to file with open (' tmp.pkl', 'wb') as f: pickle.dump (data, f) # read data with open (' tmp.pkl') from sequence file 'rb') as f: data = pickle.load (f) print (data)
Note: the way pickle opens a file must use 'rb' or' wb' to read and write even with binary.
Import jsondata = {'avers: 1,' breadth: 2, 'cations: 3,' dudes: 4, 'eBay: 5,' hello': 6} j_data = json.dumps (data) print (j_data) with open ('data.json', 'w') as f: json.dump (data, f) # read data with open (' data.json', 'r') as f: data = json.load (f) print (data)
The way json opens a file must use'r'or'w 'even if it reads and writes in binary.
This is the end of the pickle and json modules on how to understand serialization. I hope the above can be of some help and learn more. If you think the article is good, you can share it for more people to see.