Search code examples
pythonnestedmarshmallowdata-class

How should I add a field containing a list of dictionaries in Marshmallow Python?


In Marshmallow in order to have a list field you can use:

include_in = fields.List(cls_or_instance=fields.Str(),
                         default=['sample1', 'sample2'])

This is OK, but I have a new requirement to have a list of dictionaries in a field. A sample payload:

[{
  "name": "Ali",
  "age": 20
},
{
  "name": "Hasan",
  "age": 32
}]

This payload is part of the bigger schema, so now the question is how should I add and validate such a field?


EDIT-1: I went a step further and could find out that there is a Dict field type in Marshmallow so until now I have the below code sample:

fields.List(fields.Dict(
        keys=fields.String(validate=OneOf(('name', 'age'))),
        values=fields.String(required=True)
))

Now new problem arise and I cannot set different data types for fields in the dictionary (name and age). I'd be happy if someone could shed some light on this.


Solution

  • If the items in the list have the same shape, you can use a nested field within fields.List, like so:

    class PersonSchema(Schema):
        name = fields.Str()
        age = fields.Int()
    
    class RootSchema(Schema):
        people = fields.List(fields.Nested(PersonSchema))