How to Create Serializers and Deserializers from Scratch in Python



This content originally appeared on Level Up Coding – Medium and was authored by Nikhil Mahajan

Thumbnail desinged by Nikhil Mahajan

In today’s world of APIs, microservices, and data pipelines, serialization and deserialization play a central role. While Python provides built-in tools like json and pickle, understanding how to build your own serializer/deserializer helps you grasp what's happening under the hood and makes you a better developer.

In this blog, I will walk you through how to implement custom serializers and deserializers from scratch, including support for basic types and custom classes.

What Are Serializers and Deserializers?

Serialization is the process of converting the state of an object into a format that can be stored (e.g., in a file or database) or transmitted (e.g., over a network). The reverse process, recreating the object from this format, is called deserialization. Essentially, serialization allows you to save and later restore the state of an object.

Step 1: Basic Serializer for Built-in Types

Let’s start simple. We want to convert Python objects (like int, list, dict) into a JSON-like string

def serialize(obj):
if isinstance(obj, str):
return f'"{obj}"'
elif isinstance(obj, bool):
return "true" if obj else "false"
elif obj is None:
return "null"
elif isinstance(obj, (int, float)):
return str(obj)
elif isinstance(obj, list):
return "[" + ", ".join(serialize(item) for item in obj) + "]"
elif isinstance(obj, dict):
items = [f'"{key}": {serialize(value)}' for key, value in obj.items()]
return "{" + ", ".join(items) + "}"
else:
raise TypeError(f"Type {type(obj)} not supported")

Example

data = {
"name": "ABC",
"age": 21,
"languages": ["Python", "JavaScript"],
"student": True
}

print(serialize(data))

Output

{"name": "ABC", "age": 21, "languages": ["Python", "JavaScript"], "student": true}

Step 2: Basic Deserializer

Now, let’s convert that string back into a Python object. Instead of writing a full parser, we’ll use ast.literal_eval for safety and simplicity

import ast

def deserialize(data_str):
try:
# Replace JSON-like keywords with Python equivalents
safe_str = data_str.replace("null", "None").replace("true", "True").replace("false", "False")
return ast.literal_eval(safe_str)
except Exception as e:
raise ValueError("Deserialization failed: " + str(e))

Example

json_str = '{"name": "ABC", "age": 21, "languages": ["Python", "JavaScript"], "student": true}'
python_obj = deserialize(json_str)

Step 3: Support for Custom Classes

Define a class

class Student:
def __init__(self, name, age):
self.name = name
self.age = age

Custome Serializer :

def serialize_custom(obj):
if hasattr(obj, '__dict__'):
obj_dict = obj.__dict__.copy()
obj_dict['__class__'] = obj.__class__.__name__
return serialize(obj_dict)
return serialize(obj)

Custome Deserializer :

def deserialize_custom(data_str):
obj = deserialize(data_str)
if '__class__' in obj:
class_name = obj.pop('__class__')
if class_name == 'Student':
return Student(**obj)
return obj

Try what we have build :

s = Student("ABC", 21)
s_str = serialize_custom(s)
print(s_str)

s_obj = deserialize_custom(s_str)
print(s_obj.__class__, s_obj.name, s_obj.age)

Why Not Just Use json or pickle?

You should! in production But… there are specific situations where building your own serializer/deserializer makes sense. While built-in serializers like json are fantastic for most situations, building your own gives you flexibility, deeper control, and a better understanding of what’s happening under the hood.

Conclusion

That’s it! You’ve now built a basic functioning JSON serializer/deserialize in Python. While it’s far from perfect, you could enhance it with custom formatting options, support for string escaping, and more precise error reporting. Still, I hope you’ve learned something valuable from this article and that it inspires you to explore everyday tools and create something cool.

Thank you for reading this article!

Any questions or suggestions? Feel free to write a comment.

I’d also be happy if you followed me and gave this article a few claps! 😊


How to Create Serializers and Deserializers from Scratch in Python was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding – Medium and was authored by Nikhil Mahajan