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

Compare the differences between Python serialization modules pickle and json

巴扎黑
Release: 2017-09-19 10:10:21
Original
1159 people have browsed it

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.
Copy after login

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
Copy after login

Result:

{'name':'python', 'site':'pythontab.com'}
Copy after login

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)
Copy after login

Result:

{"name":"python", "site":"pythontab.com"} <type &#39;str&#39;>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template