Briefly talk about json and pickle in Python

  • 2020-06-12 09:47:07
  • OfStack

Here are two modules for serialization:

The & # 8226; json: For converting between string and python data types

The & # 8226; pickle: For converting between python-specific types and python data types

Json module provides four functions: dumps, dump, loads and load

The pickle module provides four functions: dumps, dump, loads and load


import pickle
data = {'k1':123, 'k2':888}
#dumps Data types can be converted to only python To recognize the string 
p_str = pickle.dumps(data)
print p_str


 Output results: 

(dp0
S'k2'
p1
I888
sS'k1'
p2
I123
s.

Converts the data to a string recognized only by Python and writes to the file:


import pickle
data = {'k1':123, 'k2':888}
# Open the file, and then will data write 
with open('data.pkl', 'wb') as f:
 pickle.dump(data, f)
# You also need to open the file when you read it 
with open('data.pkl', 'rb') as f:
 data_1 = pickle.load(f)
print data_1


 Results: 

{'k2': 888, 'k1': 123}

 The contents shown in the file are the same as above 1 to 

json is used in the same way as pickle


import json
data = {'k1':123, 'k2':888}
p_str = json.dumps(data)
print p_str, type(p_str)


 The results of :

{"k2": 123, "k1": 888} <type 'str'>

It looks like a dictionary, but notice that it's actually a string, because json can only be a string format, it just looks like a dictionary.


import json
data = {'k1':123, 'k2':123}
 
# Open the file, and then will data write 
with open('data.pkl', 'w') as f:
 json.dump(data, f)
 
# You also need to open the file when you read it 
with open('data.pkl', 'r') as f:
 data_1 = json.load(f)
print(data_1, type(data_1))


 Results: 

({u'k2': 123, u'k1': 123}, <type 'dict'>)

It can be read, and the type is correct.

What is the difference between pickle and json?

In the above two sections, pickle writes and reads files in 'b' mode, while json does not.

json can exchange data between different languages, while pickle is only used between python.

json serializes only the most basic data types, while pickle serializes all data types, including classes and functions.


Related articles: