亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python使用Marshmallow輕松實(shí)現(xiàn)序列化和反序列化

 更新時(shí)間:2025年03月05日 11:22:54   作者:花小姐的春天  
這篇文章主要為大家詳細(xì)介紹了Python如何使用Marshmallow輕松實(shí)現(xiàn)序列化和反序列化,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解下

可能很多Python開發(fā)者都遇到過——序列化。你可能會問:花姐,序列化有什么好聊的?這不就是把對象轉(zhuǎn)成字符串、從字符串轉(zhuǎn)回來嗎?對啊,沒錯(cuò),序列化確實(shí)這么簡單。但是,當(dāng)你一開始使用Python自帶的json庫時(shí),可能會覺得很方便。但慢慢地,你會發(fā)現(xiàn),它的功能有點(diǎn)單薄,特別是在一些復(fù)雜的數(shù)據(jù)處理場景中。今天就讓我來給大家普及一下,為什么我放棄了json,而選擇了功能更強(qiáng)大的Marshmallow!

為什么放棄json庫

json庫的局限性

大家都知道,json是Python內(nèi)置的庫,支持將Python對象轉(zhuǎn)為JSON格式的字符串(序列化),以及將JSON字符串轉(zhuǎn)回Python對象(反序列化)。這在日常開發(fā)中確實(shí)夠用,尤其是對于簡單的字典、列表和字符串。但當(dāng)你的數(shù)據(jù)結(jié)構(gòu)變得復(fù)雜時(shí),json的局限性就暴露出來了。

舉個(gè)例子,假設(shè)你有一個(gè)對象,需要序列化成JSON格式,但這個(gè)對象不僅僅是普通的字典,它可能嵌套了其他對象,或者你希望在序列化時(shí)有一些特定的字段驗(yàn)證、格式化,甚至是嵌套對象的轉(zhuǎn)換——這個(gè)時(shí)候,json庫就力不從心了。

Marshmallow,拯救我!

這時(shí)候,Marshmallow應(yīng)運(yùn)而生!它不僅可以輕松地進(jìn)行序列化和反序列化,還支持對象驗(yàn)證、字段轉(zhuǎn)換、數(shù)據(jù)清洗等強(qiáng)大功能。簡直就是復(fù)雜數(shù)據(jù)操作的“超級英雄”!

Marshmallow入門:如何用Marshmallow序列化和反序列化數(shù)據(jù)

安裝Marshmallow

首先,我們來安裝Marshmallow。打開你的終端,執(zhí)行以下命令:

pip install marshmallow

定義Schema

Marshmallow的核心概念是Schema。你可以通過定義Schema來指定如何將Python對象序列化為JSON,以及如何將JSON反序列化為Python對象。

舉個(gè)例子,假設(shè)你有一個(gè)User類,需要將其轉(zhuǎn)換成JSON格式:

from marshmallow import Schema, fields

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

class UserSchema(Schema):
    name = fields.Str()
    age = fields.Int()
    email = fields.Email()

# 創(chuàng)建一個(gè)User對象
user = User(name="小李", age=30, email="xiaoli@example.com")

# 創(chuàng)建UserSchema實(shí)例
user_schema = UserSchema()

# 序列化對象(User -> JSON)
user_json = user_schema.dump(user)
print(user_json)

這里,我們定義了一個(gè)User類和一個(gè)UserSchema類,UserSchema繼承自marshmallow.Schema,并通過fields模塊定義了我們希望序列化的字段(name、ageemail)。

通過dump()方法,我們將User對象轉(zhuǎn)換成了一個(gè)JSON兼容的字典格式。打印出來的結(jié)果大概是這樣的:

{'name': '小李', 'age': 30, 'email': 'xiaoli@example.com'}

反序列化:從JSON到Python對象

除了序列化,Marshmallow還支持反序列化,也就是將JSON轉(zhuǎn)換回Python對象。下面是如何做的:

# 反序列化(JSON -> User對象)
user_data = {'name': '小周', 'age': 28, 'email': 'xiaozhou@example.com'}
user_obj = user_schema.load(user_data)
print(user_obj)

輸出將會是一個(gè)字典:

{'name': '小周', 'age': 28, 'email': 'xiaozhou@example.com'}

這時(shí)候,你的Python對象就可以正常使用了!Marshmallow會自動把輸入的JSON轉(zhuǎn)換成Python對象,并進(jìn)行驗(yàn)證。非常方便!

Marshmallow進(jìn)階:驗(yàn)證與字段轉(zhuǎn)換

字段驗(yàn)證

在日常開發(fā)中,我們通常希望確保傳入的數(shù)據(jù)是合法的,比如用戶名不能為空,年齡必須是正數(shù)。Marshmallow支持多種驗(yàn)證功能,通過fields模塊的validators可以輕松實(shí)現(xiàn)。

例如,我們希望確保用戶的年齡是大于0的:

from marshmallow import Schema, fields, validate

class UserSchema(Schema):
    name = fields.Str(required=True)
    age = fields.Int(required=True, validate=validate.Range(min=1))
    email = fields.Email(required=True)
    
# 創(chuàng)建UserSchema實(shí)例
user_schema = UserSchema()
# 測試數(shù)據(jù)
user_data = {'name': '小李', 'age': -5, 'email': 'xiaoli@example.com'}
try:
    user = user_schema.load(user_data)
except Exception as e:
    print(e) #{'age': ['Must be greater than or equal to 1.']}

如果年齡小于1,Marshmallow會拋出驗(yàn)證錯(cuò)誤,提示我們“年齡必須大于等于1”。這就是字段驗(yàn)證的強(qiáng)大之處!

字段轉(zhuǎn)換

除了驗(yàn)證,Marshmallow還支持對字段進(jìn)行轉(zhuǎn)換。例如,我們可以將一個(gè)字符串轉(zhuǎn)換為日期格式,或者將數(shù)字轉(zhuǎn)換為貨幣格式等。

from marshmallow import Schema, fields

class EventSchema(Schema):
    name = fields.Str()
    date = fields.Date()

# 反序列化時(shí),Marshmallow會自動將字符串轉(zhuǎn)為日期對象
event_data = {'name': 'Python大會', 'date': '2025-01-21'}
event_schema = EventSchema()
event_obj = event_schema.load(event_data)
print(event_obj)

輸出結(jié)果會是:

{'name': 'Python大會', 'date': datetime.date(2025, 1, 21)}

是不是很方便?通過這種方式,你可以輕松地處理各種數(shù)據(jù)格式和轉(zhuǎn)換!

Marshmallow的高級特性:嵌套Schema和自定義序列化

嵌套Schema

有時(shí)候,我們的對象不僅僅是簡單的字段,它們可能會嵌套其他對象。Marshmallow也能輕松處理這一點(diǎn)!通過定義嵌套的Schema,你可以在一個(gè)對象中包含其他對象的數(shù)據(jù)。

例如:

from marshmallow import Schema, fields

# 定義Address的Schema
class AddressSchema(Schema):
    province = fields.Str() #省
    city = fields.Str() #市

# 定義User的Schema,包含嵌套的AddressSchema
class UserSchema(Schema):
    name = fields.Str()
    age = fields.Int()
    address = fields.Nested(AddressSchema())

# 創(chuàng)建Address對象數(shù)據(jù)
user_address = dict(province="河北省",city="邯鄲市")

# 創(chuàng)建User對象數(shù)據(jù),其中包含Artist對象
user = dict(name="花姐", age=18,address=user_address)

# 創(chuàng)建UserSchema實(shí)例
schema = UserSchema()

# 使用dump方法序列化數(shù)據(jù)
result = schema.dump(user)

# 打印序列化結(jié)果
print(result)

輸出結(jié)果會是:

{'name': '花姐', 'age': 18, 'address': {'province': '河北省', 'city': '邯鄲市'}}

這個(gè)例子展示了如何在UserSchema中嵌套另一個(gè)AddressSchema,通過fields.Nested()實(shí)現(xiàn)對象的嵌套序列化。你可以輕松地序列化復(fù)雜的對象結(jié)構(gòu)。

總結(jié)

Marshmallow在Python的序列化和反序列化處理中提供了極大的靈活性和強(qiáng)大的功能。從基本的對象轉(zhuǎn)換到復(fù)雜的數(shù)據(jù)驗(yàn)證、嵌套序列化,它都能輕松搞定。比起json庫,Marshmallow更適合處理復(fù)雜的對象結(jié)構(gòu)、字段驗(yàn)證和格式轉(zhuǎn)換,讓你在處理數(shù)據(jù)時(shí)更加得心應(yīng)手。

當(dāng)然,Marshmallow也不是完美無缺的,它的學(xué)習(xí)曲線可能相對json稍微陡峭一些,但一旦掌握,你會發(fā)現(xiàn)它在工作中無比強(qiáng)大,幾乎是一個(gè)Python開發(fā)者的“必備神器”!

到此這篇關(guān)于Python使用Marshmallow輕松實(shí)現(xiàn)序列化和反序列化的文章就介紹到這了,更多相關(guān)Python Marshmallow序列化和反序列化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論