Modules available for Serialization and Deserialization in Python
Last Updated :
14 Aug, 2021
Python provides three different modules which allow us to serialize and deserialize objects :
- Marshal Module
- Pickle Module
- JSON Module
1. Marshal Module: It is the oldest module among these three. It is mainly used to read and write the compiled byte code of Python modules. Even we can use marshal to serialize Python objects, but it is not recommended to use. It is mainly used by the interpreter and the official documentation warns that the python maintainers may modify the format in backward-incompatible ways.
Note: It is recommended to never unmarshal data received from an untrusted or unauthenticated source.
Example :
Python3
# importing the module
import marshal
data = {'name': 'sunny','age': 34,'address': 'nasik'}
# dumps() return byte object stored in variable 'bytes'
bytes = marshal.dumps(data)
print('After serialization : ', bytes)
# loads() convert byte object to value
new_data = marshal.loads(bytes)
print('After deserialization : ', new_data)
Output:
After serialization : b'\xfb\xda\x04name\xda\x05sunny\xda\x03age\xe9"\x00\x00\x00\xda\x07address\xda\x05nasik0'
After deserialization : {'name': 'sunny', 'age': 34, 'address': 'nasik'}
2. Pickle Module: It is another way to serialize and deserialize Python objects. It serializes the Python object in a binary format, due to which it is not human-readable. It is faster and it also works with custom-defined objects. The Python pickle module is a better choice for serialization and deserialization of python objects. If you don't need a human-readable format or if you need to serialize custom objects then it is recommended to use the pickle module.
Example:
Python3
# importinig the module
import pickle
data = {'st_name': 'Sunny', 'st_id': '9607', 'st_add': 'Nasik'}
with open('data.pickle', 'wb') as f1 :
# converts object to byte stream(list, dict, etc.)
pickle.dump(data, f1)
print('Pickling Completed...')
with open('data.pickle', 'rb') as f2 :
print('Unpickling the data : ')
# converts byte stream(generated through pickling)back into object
data = pickle.load(f2)
print(data)
Output:
Pickling Completed...
Unpickling the data :
{'st_name': 'Sunny', 'st_id': '9607', 'st_add': 'Nasik'}
3. JSON Module: It is a newly created module. It allows us to work with standard JSON files. JSON is a widely used format for data exchange and it is very convenient. It is human-readable and language-independent, and it's lighter than XML. Using the JSON module we can serialize and deserialize several standard Python types like bool, dict, int, float, list, string, tuple, none etc. The JSON module and XML are a good choice if we want to interoperability among different languages.
Example: Deserializing
Python3
# importing the module
import json
# JSON string
students = '{"id":"9607", "name": "Sunny", "department":"Computer"}'
# convert string to Python dict
student_dict = json.loads(students)
print(student_dict)
print(student_dict['name'])
print('Deserialization Completed.')
Output:
{"id": "9607", "name": "Sunny", "department":"Computer"}
Sunny
Deserialization Completed.
Example: Serializing
Python3
# importing the module
import json
data = {
"id": "877",
"name": "Mayur",
"department": "Comp"
}
# Serializing json
json_object = json.dumps(data)
print(json_object)
print('Serialization Completed.')
Output{"id": "877", "name": "Mayur", "department": "Comp"}
Serialization Completed.
Output:
{"id": "877", "name": "Mayur", "department": "Comp"}
Serialization Completed.
Similar Reads
Flask Serialization and Deserialization Serialization and deserialization are fundamental concepts in web development, especially when working with REST APIs in Flask. Serialization refers to converting complex data types (such as Python objects) into a format that can be easily stored or transmitted, like JSON or XML. Deserialization, on
4 min read
Serialize and Deserialize complex JSON in Python JSON stands for JavaScript Object Notation. It is a format that encodes the data in string format. JSON is language-independent and because of that, it is used for storing or transferring data in files. Serialization of JSON object: It means converting a Python object (typically a dictionary) into a
3 min read
C API from Extension Module in Python | Set 2 Prerequisite: C API from Extension Module in Python | Set 1 Let's see an example of a new extension module that loads and uses these API functions that we build up in the previous article. Code #1 : C #include "pythonsample.h" /* An extension function that uses the exported API */ static P
2 min read
marshal â Internal Python object serialization Serializing a data means converting it into a string of bytes and later reconstructing it from such a string. If the data is composed entirely of fundamental Python objects, the fastest way to serialize the data is by using marshal module (For user defined classes, Pickle should be preferred). Marsh
2 min read
pickle â Python object serialization Python is a widely used general-purpose, high-level programming language. In this article, we will learn about pickling and unpickling in Python using the pickle module. The Python Pickle ModuleThe pickle module is used for implementing binary protocols for serializing and de-serializing a Python ob
9 min read
Serializing Data Using the pickle and cPickle Modules Serialization is a process of storing an object as a stream of bytes or characters in order to transmit it over a network or store it on the disk to recreate it along with its state whenever required. The reverse process is called deserialization. In Python, the Pickle module provides us the means
5 min read
Create and Import modules in Python In Python, a module is a self-contained Python file that contains Python statements and definitions, like a file named GFG.py, can be considered as a module named GFG which can be imported with the help of import statement. However, one might get confused about the difference between modules and pac
3 min read
How to create modules in Python 3 ? Modules are simply python code having functions, classes, variables. Any python file with .py extension can be referenced as a module. Although there are some modules available through the python standard library which are installed through python installation, Other modules can be installed using t
4 min read
Deserialize JSON to Object in Python Let us see how to deserialize a JSON document into a Python object. Deserialization is the process of decoding the data that is in JSON format into native data type. In Python, deserialization decodes JSON data into a dictionary(data type in python).We will be using these methods of the json module
2 min read
How to use NamedTuple and Dataclass in Python? We have all worked with classes and objects for more than once while coding. But have you ever wondered how to create a class other than the naive methods we have all been taught. Don't worry in this article we are going to cover these alternate methods. There are two alternative ways to construct a
2 min read