How to serialize and deserialize objects using pickle and JSON in Python

WBOY
Release: 2023-10-16 09:22:50
Original
1726 people have browsed it

How to serialize and deserialize objects using pickle and JSON in Python

How to serialize and deserialize objects using pickle and JSON in Python

Python is a simple yet powerful programming language with many useful built-in libraries and modules that enable developers to quickly perform a variety of tasks. Among them, pickle and JSON are two commonly used modules for object serialization and deserialization. This article will introduce how to use these two modules to serialize and deserialize objects, and provide detailed code examples.

  1. Use pickle for object serialization and deserialization

pickle is a module in Python through which objects can be converted into binary data for storage or transmission. , and can also restore binary data to the original object.

First, we need to import the pickle module:

import pickle
Copy after login

Next, we can use the dumps function of the pickle module to serialize the object into binary data:

data = {'name':'Tom', 'age': 25, 'city': 'New York'}
serialized_data = pickle.dumps(data)
Copy after login

Use the dumps function After that, the variable serialized_data will hold the serialized binary data. On the contrary, we can use the loads function to restore the binary data to the original object:

deserialized_data = pickle.loads(serialized_data)
print(deserialized_data)
Copy after login

At this time, the variable deserialized_data will save the restored original object.

The following is a complete example showing how to serialize and deserialize a custom Person object:

import pickle

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# 序列化对象
person = Person('Tom', 25)
serialized_person = pickle.dumps(person)

# 反序列化对象
deserialized_person = pickle.loads(serialized_person)
print(deserialized_person.name)
print(deserialized_person.age)
Copy after login
  1. Using JSON for object serialization and deserialization JSON is a lightweight data exchange format that is easy to read and write. Python provides the json module, which can easily serialize and deserialize JSON objects.
First, we need to import the json module:

import json
Copy after login

Next, we can use the dumps function of the json module to serialize the object into a JSON string:

data = {'name':'Tom', 'age': 25, 'city': 'New York'}
serialized_data = json.dumps(data)
Copy after login

Use dumps After the function, the variable serialized_data will hold the serialized JSON string. On the contrary, we can use the loads function to restore the JSON string to the original object:

deserialized_data = json.loads(serialized_data)
print(deserialized_data)
Copy after login

At this time, the variable deserialized_data will save the restored original object.

Similarly, here is a complete example showing how to serialize and deserialize a custom Person object:

import json

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# 序列化对象
person = Person('Tom', 25)
serialized_person = json.dumps(person.__dict__)

# 反序列化对象
deserialized_person = json.loads(serialized_person)
print(deserialized_person['name'])
print(deserialized_person['age'])
Copy after login
Summary:

Passed With these two modules, pickle and JSON, we can easily serialize and deserialize objects. Use pickle to convert objects into binary data, which can be used for file storage and network transmission; and JSON, as a universal data exchange format, can easily exchange data with other languages. According to the specific usage scenarios and needs, we can choose the appropriate module to perform object serialization and deserialization operations.

The above is the detailed content of How to serialize and deserialize objects using pickle and JSON in Python. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!