Search code examples
pythonjsondeserializationmarshmallow

How do I deserialize a different structured JSON data in Marshmallow?


I have a Schema as below:

from marshmallow import Schema, fields

class ContactSchema(Schema):
    # ... other fields ...
    phone = fields.Str()
    # ... other fields ...

However, JSON data I deal with is different:

{
    // ... other data ...
    "information": {
        "address": "foo",
        "email": "[email protected]",
        "phone": "+101234567890"
    }
    // .. other data ..
}

As you can see, phone key is under information, which is different than how ContactSchema is formed.

Can I, and how can I, map a Field under a Schema to a different path in target JSON data?


Environment

  • Python 3.5 and above
  • Marshmallow 2.16.3

Solution

  • You can extend your schema and provide a pre_load method:

    class ContactSchema(Schema):
    
        @preload
        def extract_information(self, data):
           # Please check for None's
           data['phone'] = data['information'].pop('phone')
           return data