Modules available for Serialization and Deserialization in Python - GeeksforGeeks

14 Aug, 2021
Python provides three different modules which allow us to serialize and deserialize objects :  
Marshal ModulePickle ModuleJSON Module
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 moduleimport 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 valuenew_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 moduleimport 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 moduleimport json   # JSON stringstudents = '{"id":"9607", "name": "Sunny", "department":"Computer"}'   # convert string to Python dictstudent_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 moduleimport json    data = {  "id": "877",  "name": "Mayur",  "department": "Comp"}    # Serializing json json_object = json.dumps(data)print(json_object)print('Serialization Completed.')
{"id": "877", "name": "Mayur", "department": "Comp"}
Serialization Completed.
Output:
{"id": "877", "name": "Mayur", "department": "Comp"}
Serialization Completed. 
gabaa406
sagar0719kumar
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()