gpt4 book ai didi

python - 使用 Marshmallow 反序列化复杂的 JSON

转载 作者:行者123 更新时间:2023-12-05 06:32:33 27 4
gpt4 key购买 nike

我需要反序列化这个 JSON:

{
"emails": {
"items": [
{
"id": 1,
"email": "john@doe.com"
},
{
"id": 2,
"email": "jane@doe.com"
}
]
}
}

使用 Marshmallow 进入这个对象:

{
"emails": [
{
"id": 1,
"email": "john@doe.com"
},
{
"id": 2,
"email": "jane@doe.com"
}
]
}

我该怎么做?

我试过这种方式,我发现它更直观,但它不起作用:

class Phone(OrderedSchema):
id = fields.Int()
email = fields.Str()

class Contact(Schema):
key = fields.Str()
phones = fields.Nested(Phone, load_from='phones.list', many=True)

最佳答案

使用下面的代码,我用的是Dict和Nested:

from marshmallow import Schema, fields, post_load


class Contact(Schema):
"""Schema for emails."""

# Define subschema for serializing each item
class Item(Schema):
"""Subclass for each item."""

id = fields.Integer(required=True)
email = fields.Email(required=True)


# Define the fields in the main schema, here we define "emails" as a dict that accepts
# strings for keys and list of Item(Schema) as values
emails = fields.Dict(keys=fields.String(), values=fields.Nested(Item, many=True))

# Define the way you want the schema to return the data
@post_load
def deserialize(self, data, **kwargs):
"""Deserialize in an specific way."""
# post_load needs to return the data that the schema will return after deserialization

return {
"emails": [item for item in data["emails"]["items"]]
}

Contact().load({
"emails": {
"items": [
{
"id": 1,
"email": "john@doe.com"
},
{
"id": 2,
"email": "jane@doe.com"
}
]
}
})
# Returns
#{'emails': [{'email': 'john@doe.com', 'id': 1},
# {'email': 'jane@doe.com', 'id': 2}]}

关于python - 使用 Marshmallow 反序列化复杂的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51194708/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com