Home  >  Article  >  Backend Development  >  Compare the differences between Python serialization modules pickle and json

Compare the differences between Python serialization modules pickle and json

巴扎黑
巴扎黑Original
2017-09-19 10:10:211114browse

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

pickle usage

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

Usage of json

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 &#39;str&#39;>

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.

What is the difference between pickle and json?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn