Object Serialization in Python

Have you ever found yourself in a situation where you need to convert custom objects into JSON objects / dictionaries and vice versa? If so, this article might give you some serious help!

Bill Tran
Bill Tran
Dec 10, 2020 · 7 min read
Photo by @joyfulcaptures on unsplash.com

Problem

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person(name='Bill', age=19)
return_value = {
'name': person.name,
'age': person.age
}
request_payload = {
'name': 'Bill',
'age': 19,
'job': 'student'
}
bill = Person(
name = request_payload['name'],
age = request_payload['age']
)

1. Serialization and Deserialization

1.1. Serialization

1.2. Deserialization

2. Marshmallow

2.1. What is Marshmallow?

2.2. How to use Marshmallow?

Install

pip install marshmallow

Define a Schema

from marshmallow import Schema, fieldsclass PersonSchema(Schema):
name = fields.Str()
age = fields.Int()

Validate inputs

data = {
'name': 'bill',
'age': 'nineteen'
}
person = PersonSchema().load(data)
ValidationError: {'age': ['Not a valid integer.']}

Serialize objects

person = Person(name='bill', age=19)
serialized_value = PersonSchema().dump(person)
# {
# 'name': 'bill',
# 'age': 19,
# }

Pass arguments into Schema fields

from marshmallow import Schema, fields, validateclass EmployeeSchema(Schema):
name = fields.Str(
required=True,
error_messages={
"required": "Name is missing.",
"type": "Name must be a string."
}
)
age = fields.Int(required=True, validate=validate.Range(min=18))
skills = fields.Str(many=True, allow_none=True)
home_address = fields.Str(data_key='address', default='Hanoi')

Nest schemas

from marshmallow import Schema, fields
class PersonSchema(Schema):
name = fields.Str()
age = fields.Int()
class HouseSchema(Schema):
address = fields.Str()
class FamilySchema(HouseSchema):
people = fields.Nested(PersonSchema, many=True)

Perform transformation before and after dump or load

from marshmallow import Schema, fields, post_loadclass PersonSchema(Schema):
name = fields.Str()
age = fields.Int()
@post_load
def make_person(self, data, **__):
return Person(**data)

2.3. Why should we use Marshmallow?

Agnostic

Concise, familiar, and reusable syntax

High configurability

Conclusion

The Startup

Get smarter at building your thing. Join The Startup’s +725K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store