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.
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
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)
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)
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)
import json
data = {'name':'Tom', 'age': 25, 'city': 'New York'} serialized_data = json.dumps(data)
deserialized_data = json.loads(serialized_data) print(deserialized_data)
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'])
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!