Serialize and deserialize a Python object
This post will discuss how to serialize and deserialize an object in Python.
1. Using pickle.dump() function
Python offers a pickle module that implements binary protocols for serializing and deserializing a Python object.
The idea is to use the pickle.dump(obj, file) function, which converts the Python object obj into a byte stream and then writes it to the file object file. To do the inverse, i.e., convert the byte stream from a binary file back into a Python object, use the pickle.load() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import pickle # object to be serialized x = [1, 2, 3, 4, 5] # serialize with open('output.dat', 'wb') as f: pickle.dump(x, f) # deserialize with open('output.dat', 'rb') as f: data = pickle.load(f) print((data, type(data))) |
Note that pickle suffers from arbitrary code execution vulnerability and should not be used to process data from an untrusted source.
2. Using json.dumps() function
Alternatively, you can use the json module, a standard library module allowing JSON serialization and deserialization. The Json format is a secure, human-readable text serialization format, unlike pickle, which is an unsecure binary serialization format that is not human-readable.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import json # object to be serialized x = [1, 2, 3, 4, 5] # serialize with open('output.dat', 'w') as f: str = json.dumps(x) f.write(str) # deserialize with open('output.dat', 'r') as f: s = f.read() data = json.loads(s) print((data, type(data))) |
3. Using simplejson.dump() function
Another option is to use the simplejson module, which exposes a similar API to the pickle module. Here’s an example of its usage:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import simplejson # object to be serialized x = [1, 2, 3, 4, 5] # serialize with open('output.dat', 'w') as f: str = simplejson.dump(x, f) # deserialize with open('output.dat', 'r') as f: data = simplejson.load(f) print((data, type(data))) |
That’s all about serializing and deserializing a Python object.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)