[Python] Creating nested JSON objects from a flat Python object using Marshmallow and...

Discussão em 'Python' iniciado por Stack, Maio 24, 2025.

  1. Stack

    Stack Membro Participativo

    Given a simple model (in reality SQLAlchemy):

    class Thing():
    name: str
    attr1: int
    attr2: str


    How would I write the associated Marshmallow Schema class such that it produced JSON like this - ideally without using fields.Method so that I can do things like fields.Integer(as_string=True) where needed.

    {
    "name": "Name",
    "attributes": {
    "attr1": "1",
    "attr2": "attr2"
    }
    }


    As it stands i've done something like this, but I'd prefer a non-custom method way if possible. Having to coerce into str() for example feels like i'm missing out on the features of marshmallow ... I'm unsure unsure how deserialising will work.

    attributes = fields.Method("build_attributes")
    def build_attributes(self, obj):
    return { "attr1": str(obj.attr1), "attr2": obj.attr2 }

    Continue reading...

Compartilhe esta Página