Bird
Raised Fist0
PythonHow-ToBeginner · 3 min read

How to Deserialize Object in Python: Simple Guide

To deserialize an object in Python, use the pickle.load() function for binary data or json.loads() for JSON strings. Deserialization converts stored data back into Python objects.
📐

Syntax

Deserialization means converting stored data back into Python objects. Common methods include:

  • pickle.load(file): Reads a binary file and returns the original Python object.
  • json.loads(string): Converts a JSON string into Python data types like dict or list.
python
import pickle
import json

# Using pickle to deserialize from a file
with open('data.pkl', 'rb') as file:
    obj = pickle.load(file)

# Using json to deserialize from a string
json_string = '{"name": "Alice", "age": 30}'
obj = json.loads(json_string)
💻

Example

This example shows how to deserialize a Python dictionary saved as JSON and a list saved with pickle.

python
import pickle
import json

# JSON deserialization example
json_data = '{"city": "Paris", "population": 2148327}'
city_info = json.loads(json_data)
print(city_info)

# Pickle deserialization example
sample_list = [10, 20, 30]
# First, serialize the list to a file
with open('list.pkl', 'wb') as f:
    pickle.dump(sample_list, f)

# Now, deserialize it back
with open('list.pkl', 'rb') as f:
    loaded_list = pickle.load(f)
print(loaded_list)
Output
{'city': 'Paris', 'population': 2148327} [10, 20, 30]
⚠️

Common Pitfalls

Common mistakes when deserializing include:

  • Trying to deserialize data with the wrong method (e.g., using json.loads() on binary pickle data).
  • Not opening files in the correct mode ('rb' for reading binary pickle files).
  • Security risks: never deserialize data from untrusted sources as it can run harmful code (especially with pickle).
python
import pickle

# Wrong: opening pickle file in text mode
try:
    with open('data.pkl', 'r') as f:
        obj = pickle.load(f)  # This will raise an error
except Exception as e:
    print(f"Error: {e}")

# Right: open in binary mode
with open('data.pkl', 'rb') as f:
    obj = pickle.load(f)
Output
Error: a bytes-like object is required, not 'str'
📊

Quick Reference

MethodUse CaseFile Mode / Input Type
pickle.load(file)Deserialize Python objects from binary files'rb' (read binary)
pickle.loads(bytes)Deserialize Python objects from bytesbytes input
json.loads(string)Deserialize JSON string to Python dict/liststring input
json.load(file)Deserialize JSON from text file'r' (read text)
✅

Key Takeaways

Use pickle.load() to deserialize Python objects from binary files safely.
Use json.loads() to convert JSON strings into Python data types.
Always open files in the correct mode: 'rb' for pickle, 'r' for JSON text.
Never deserialize data from untrusted sources to avoid security risks.
Match the deserialization method to the data format to avoid errors.