0

I am new to using flask/marshmallow and I have an object that looks like this:

{'field_0': {'field_1': {'field_2': {'field_3': '...', 'value': 'this is the value I want'}}}}

Is it possible to define a schema for this using marshmallow without creating 4 nested classes?

MJR
  • 35
  • 9

1 Answers1

0

Not really.

Here is the canonical way (dropping 2 levels to simplify the example)

class Inner(ma.Schema):
    field_3 = ma.fields.IntField()
    value = ma.fields.StringField()

class Outer(ma.Schema):
    field_1 = ma.fields.Nested(Inner)

You could use from_dict:

Outer = ma.Schema.from_dict("field_1": ma.fields.Nested(ma.Schema.from_dict("field_3": ma.fields.Int(), "value": ma.fields.String())

You could also invent complex way with metaprogramming (using type to build schema classes) but overall the simplest way is the first one above.

Jérôme
  • 13,328
  • 7
  • 56
  • 106