These are two modules used for serialization:
• json: used to convert between strings and python data types
• pickle: used for python-specific types and Convert between python data types
The Json module provides four functions: dumps, dump, loads, load
The pickle module provides four functions: dumps, dump, loads, load
dumps can convert the data type into a serialized (only recognized by python) string
>>> import pickle >>> data = {'name':'python', 'site':'pythontab.com'} >>> pstr = pickle.dumps(data) >>> print pstr (dp0 S'name' p1 S'python' p2 sS'site' p3 S'pythontab.com' p4 s.
Convert the data into a serialized string and write it File:
import pickle data = {'name':'python', 'site':'pythontab.com'} #打开文件,然后将data写入 with open('dump.data', 'wb') as f: pickle.dump(data, f) #同样读取的时候也需要打开文件 with open('dump.data', 'rb') as f: data_load = pickle.load(f) print data_load
Result:
{'name':'python', 'site':'pythontab.com'}
The content displayed in the file is consistent with the above
The usage of json is the same as pickle
import json data = {'name':'python', 'site':'pythontab.com'} jstr = json.dumps(data) print jstr, type(jstr)
Result:
{"name":"python", "site":"pythontab.com"} <type 'str'>
Note: It looks like a dictionary, but be careful, it is actually a string. Because json can only be in string format, it just looks like a dictionary.
Json can exchange data between different languages, while pickle can only be used between python.
Json can only serialize the most basic data types, while pickle can serialize all data types, including classes and functions.
The above is the detailed content of Compare the differences between Python serialization modules pickle and json. For more information, please follow other related articles on the PHP Chinese website!