【问题标题】:Deserialize complex JSON using Marshmallow使用 Marshmallow 反序列化复杂的 JSON
【发布时间】:2018-12-14 03:16:59
【问题描述】:

我需要反序列化这个 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)

【问题讨论】:

    标签: python deserialization marshmallow


    【解决方案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}]}
    

    【讨论】:

      猜你喜欢
      • 2020-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-09
      • 2021-12-20
      • 1970-01-01
      相关资源
      最近更新 更多