Let's talk about Python's implementation of data serialization operations

PHPz
Release: 2023-04-12 09:31:12
forward
2071 people have browsed it

​In daily development, serializing and deserializing data are common data operations. Python provides two modules to facilitate developers to implement data serialization operations, namely the json module and the pickle module. The main differences between these two modules are as follows:

  • json is a text serialization format, while pickle is a binary serialization format;
  • json is something we can read intuitively, while pickle is No;
  • json is interoperable and widely used outside the Python system, while pickle is exclusive to Python;
  • By default, json can only represent Python built-in types Subset cannot represent custom classes; but pickle can represent a large number of Python data types.

Let's talk about Python's implementation of data serialization operations

Json module

Json is a lightweight data exchange format. Due to its small amount of transmitted data and easy parsing of the data format With its characteristics, it is widely used in interactive operations between various systems to transfer data as a data format. It contains multiple commonly used functions, as follows:

dumps() function

dumps() function can encode Python objects into Json strings. For example:

#字典转成json字符串 加上ensure_ascii=False以后,可以识别中文, indent=4是间隔4个空格显示 

import json 
d={'小明':{'sex':'男','addr':'上海','age':26},'小红':{ 'sex':'女','addr':'上海', 'age':24},}
print(json.dumps(d,ensure_ascii=False,indent=4)) 

#执行结果:
{
"小明": {
"sex": "男",
"addr": "上海",
"age": 26
},
"小红": {
"sex": "女",
"addr": "上海",
"age": 24
}
}
Copy after login

dump() function

dump() function can encode Python objects into json strings and automatically write them to files, without the need to write separate files. For example:

#字典转成json字符串,不需要写文件,自动转成的json字符串写入到‘users.json’的文件中 
import json 
d={'小明':{'sex':'男','addr':'上海','age':26},'小红':{ 'sex':'女','addr':'上海', 'age':24},}
#打开一个名字为‘users.json’的空文件
fw =open('users.json','w',encoding='utf-8')

json.dump(d,fw,ensure_ascii=False,indent=4)
Copy after login

loads() function

loads() function can convert a json string into a Python data type. For example:

#这是users.json文件中的内容
{
"小明":{
"sex":"男",
"addr":"上海",
"age":26
},
"小红":{
"sex":"女",
"addr":"上海",
"age":24
}
}

#!/usr/bin/python3
#把json串变成python的数据类型 
import json
#打开‘users.json’的json文件
f =open('users.json','r',encoding='utf-8')
#读文件
res=f.read()
print(json.loads(res)) 

#执行结果:
{'小明': {'sex': '男', 'addr': '上海', 'age': 26}, '小红': {'sex': '女', 'addr': '上海', 'age': 24}}
Copy after login

load() function

load() has similar functions to loads(). The load() function can convert json strings into Python data types. The difference is the parameters of the former. It is a file object and there is no need to read this file separately. For example:

#把json串变成python的数据类型:字典,传一个文件对象,不需要再单独读文件 
import json 
#打开文件
f =open('users.json','r',encoding='utf-8') 
print(json.load(f))

#执行结果:
{'小明': {'sex': '男', 'addr': '上海', 'age': 26}, '小红': {'sex': '女', 'addr': '上海', 'age': 24}}
Copy after login

Pickle module

The Pickle module has similar functions to the Json module and also contains four functions, namely dump(), dumps(), loads() and load(). The main differences are as follows:

The difference between dumps and dump is that the former serializes the object, while the latter serializes the object and saves it to a file.

The difference between loads and load is that the former deserializes the serialized string, while the latter reads the serialized string from the file and deserializes it.

dumps() function

dumps() function can convert data into a string that is only recognized by python language in a special form, for example:

import pickle
# dumps功能
import pickle
data = ['A', 'B', 'C','D']
print(pickle.dumps(data))

b'x80x03]qx00(Xx01x00x00x00Aqx01Xx01x00x00x00Bqx02Xx01x00x00x00Cqx03Xx01x00x00x00Dqx04e.'
Copy after login

dump() function

The dump() function can convert data into a string recognized only by the Python language in a special form and write it to a file. For example:

# dump功能
with open('test.txt', 'wb') as f:
pickle.dump(data, f)
print('写入成功')

写入成功
Copy after login

loads() function

loads() function can convert pickle data into python data structure. For example:

# loads功能
msg = pickle.loads(datastr)
print(msg)

['A', 'B', 'C', 'D']
Copy after login

load() function

load() function can read data from a data file and convert it into a python data structure. For example:

# load功能
with open('test.txt', 'rb') as f:
 data = pickle.load(f)
print(data)

['A', 'B', 'C', 'D']
Copy after login

Summary

This section introduces you to the common operations of the json&pickle module in Python, which provides support for serializing and deserializing data.


The above is the detailed content of Let's talk about Python's implementation of data serialization operations. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:51cto.com
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