Many Python developers may have encountered it-Serialization. You may ask: Sister Hua, what is there to talk about in serialization? Isn't this just converting the object into a string and back from a string? Yes, yes, serialization is indeed that simple. However, when you start using Python's ownjson
When library, it may feel very convenient. But slowly, you will find that its functions are a bit thin, especially in some complex data processing scenarios. Today I will let me share with you why I gave upjson
, and choose a more powerful oneMarshmallow!
Why give up the json library
Limitations of json library
Everyone knows thatjson
It is a built-in library in Python that supports converting Python objects to strings in JSON format (serialization), and converting JSON strings back to Python objects (deserialization). This is indeed sufficient in daily development, especially for simple dictionaries, lists and strings. But when your data structure becomes complex,json
The limitations of the
For example, suppose you have an object that needs to be serialized into JSON format, but this object is not just a normal dictionary, it may be nested with other objects, or you want to have some specific field validation, formatting, or even conversion of nested objects during serialization - at this time,json
Ku was unable to do so.
Marshmallow, save me!
At this time,MarshmallowBorn in the future! It not only allows easy serialization and deserialization, but also supports powerful functions such as object verification, field conversion, and data cleaning. It's simply a "superhero" of complex data operations!
Getting started with Marshmallow: How to serialize and deserialize data with Marshmallow
Install Marshmallow
First, let's install Marshmallow. Open your terminal and execute the following command:
pip install marshmallow
Definition Schema
The core concept of Marshmallow isSchema. You can specify how to serialize Python objects to JSON by defining Schema, and how to deserialize JSON to Python objects.
For example, suppose you have oneUser
class, it needs to be converted to JSON format:
from marshmallow import Schema, fields class User: def __init__(self, name, age, email): = name = age = email class UserSchema(Schema): name = () age = () email = () # Create a User objectuser = User(name="Little Li", age=30, email="xiaoli@") # Create a UserSchema instanceuser_schema = UserSchema() # Serialize object (User -> JSON)user_json = user_schema.dump(user) print(user_json)
Here, we define aUser
Class and oneUserSchema
kind,UserSchema
Inherited from, and pass
fields
The module defines the fields we want to serialize (name
、age
andemail
)。
passdump()
Method, we willUser
The object is converted into a JSON-compatible dictionary format. The print result is probably like this:
{'name': 'Xiao Li', 'age': 30, 'email': 'xiaoli@'}
Deserialization: From JSON to Python object
In addition to serialization, Marshmallow also supports deserialization, that is, converting JSON back to Python objects. Here's how to do it:
# Deserialization (JSON -> User object)user_data = {'name': 'Xiao Zhou', 'age': 28, 'email': 'xiaozhou@'} user_obj = user_schema.load(user_data) print(user_obj)
The output will be a dictionary:
{'name': 'Xiaozhou', 'age': 28, 'email': 'xiaozhou@'}
At this time, your Python object can be used normally! Marshmallow will automatically convert the input JSON into Python objects and verify it. Very convenient!
Marshmallow Advanced: Verification and Field Conversion
Field Verification
In daily development, we usually want to ensure that the incoming data is legal, such as the username cannot be empty and the age must be a positive number. Marshmallow supports multiple verification functions,fields
ModularvalidatorsIt can be easily achieved.
For example, we want to make sure that the user's age is greater than 0:
from marshmallow import Schema, fields, validate class UserSchema(Schema): name = (required=True) age = (required=True, validate=(min=1)) email = (required=True) # Create a UserSchema instanceuser_schema = UserSchema() # Test datauser_data = {'name': 'Little Li', 'age': -5, 'email': 'xiaoli@'} try: user = user_schema.load(user_data) except Exception as e: print(e) #{'age': ['Must be greater than or equal to 1.']}
If the age is less than 1, Marshmallow will throw a verification error, prompting us that "the age must be greater than or equal to 1". This isField VerificationThe power of it!
Field conversion
In addition to verification, Marshmallow also supports conversion of fields. For example, we can convert a string to date format, or convert a number to currency format, etc.
from marshmallow import Schema, fields class EventSchema(Schema): name = () date = () # When deserializing, Marshmallow will automatically convert the string to a date objectevent_data = {'name': 'Python Conference', 'date': '2025-01-21'} event_schema = EventSchema() event_obj = event_schema.load(event_data) print(event_obj)
The output result will be:
{'name': 'Python Conference', 'date': (2025, 1, 21)}
Isn't it very convenient? In this way, you can easily handle various data formats and conversions!
Advanced features of Marshmallow: Nested Schema and custom serialization
Nested Schema
Sometimes our objects are more than just simple fields, they may be nested with other objects. Marshmallow can handle this easily, too! By defining nestedSchema
, you can include data from other objects in one object.
For example:
from marshmallow import Schema, fields # Define Address's Schemaclass AddressSchema(Schema): province = () #Province city = () #city # Define the User's Schema, including nested AddressSchemaclass UserSchema(Schema): name = () age = () address = (AddressSchema()) # Create Address object datauser_address = dict(province="Hebei Province",city="Handan City") # Create User object data, which contains Artist objectuser = dict(name="Sister Hua", age=18,address=user_address) # Create a UserSchema instanceschema = UserSchema() # Serialize data using dump methodresult = (user) # Print serialization resultsprint(result)
The output result will be:
{'name': 'Sister Hua', 'age': 18, 'address': {'province': 'Hebei Province', 'city': 'Handan City'}}
This example shows how toUserSchema
Nested another one inAddressSchema
,pass()
Implement nested serialization of objects. You can easily serialize complex object structures.
Summarize
Marshmallow provides great flexibility and powerful functions in Python serialization and deserialization processing. It can be easily done from basic objects to complex data verification and nested serialization. Compared tojson
The library, Marshmallow is more suitable for handling complex object structures, field verification and format conversion, making you more comfortable when processing data.
Of course, Marshmallow is not perfect either, its learning curve may be relativelyjson
It's a little steeper, but once you master it, you'll find it extremely powerful at work, almost a "must-have artifact" for Python developers!
This is the article about Python using Marshmallow to easily implement serialization and deserialization. For more related Python Marshmallow serialization and deserialization content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!