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.

Download Code

 
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.

Download Code

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:

Download Code

That’s all about serializing and deserializing a Python object.