使用棉花糖反序列化复杂的JSON

时间:2018-07-05 15:09:32

标签: python deserialization marshmallow

我需要反序列化此JSON:

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

使用棉花糖进入该对象:

{
    "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)

1 个答案:

答案 0 :(得分:1)

使用以下代码,我使用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}]}
相关问题