自动使用Marshm解析嵌套模式的字典键套接字

2024-06-16 10:30:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我在字典里定义了一个对象的另一部分。我希望在反序列化对象时自动解析键。我怎样才能以惯用的方式在棉花糖中达到这种效果呢?在

目前的解决方法是手动解析所有的引用,但这看起来很笨拙,因为棉花糖的声明性特性应该能够自动为我们完成。在

注意,Marshmallow SQLAlchemy在columns are declared as relationships“时支持这种(反)序列化,这会自动为我们做到这一点,但我想用JSON数据来实现。在

下面是我想要实现的一个例子,fields.Relationship是一个还不存在的东西:

class UserSchema(Schema):
    name = fields.String()
    email = fields.Email()
    friends = fields.Relationship('self', path="AddressBook.contacts", many=True)

class AddressBookSchema(Schema):
    contacts = nested.Dict(keys=fields.String(), values=fields.Nested(UserSchema))

# ... create ``user`` ...
serialized_data = AddressBookSchema().dump(user)
pprint(serialized_data)
# "contacts": {
#   "Steve": {
#     "name": "Steve",
#     "email": "steve@example.com",
#     "friends": ["Mike"]
#   },
#   "Mike": {
#     "name": "Mike",
#     "email": "mike@example.com",
#     "friends": []
# }


deserialized_data = UserSchema().load(result)
pprint(deserialized_data)
# "contacts": {
#   "Steve": {
#     "name": "Steve",
#     "email": "steve@example.com",
#     "friends": [ {"name": "Mike", "email": "mike@example.com"]
#   },
#   "Mike": {
#     "name": "Mike",
#     "email": "mike@example.com",
#     "friends": []
# }

我还提交了一份issue on the Marshmallow Github repository。在


Tags: 对象namecomfieldsdata序列化exampleemail
1条回答
网友
1楼 · 发布于 2024-06-16 10:30:22

为什么不简单地用^{}钩子传输中间数据:

class UserSchema(Schema):
    name = fields.String()
    email = fields.Email()
    friends = fields.List(fields.String())

class AddressBookSchema(Schema):
    contacts = fields.Dict(keys=fields.String(), values=fields.Nested(UserSchema))

    @post_load
    def trans_friends(self, item):
        for name in item['contacts']:
            item['contacts'][name]['friends'] = [item['contacts'][n] for n in item['contacts'][name]['friends']]


data = """
{
 "contacts": {
  "Steve": {
    "name": "Steve",
    "email": "steve@example.com",
    "friends": ["Mike"]
  },
  "Mike": {
    "name": "Mike",
    "email": "mike@example.com",
    "friends": []
  }
 }
}
"""

deserialized_data = AddressBookSchema().loads(data)
pprint(deserialized_data)

产量:

^{pr2}$

相关问题 更多 >