How to serialize a Marshmallow field under a different name

selotape picture selotape · Jun 8, 2017 · Viewed 14.6k times · Source

I want a Marshmallow Schema with the following output json -

{
  "_id": "aae216334c3611e78a3e06148752fd79",
  "_time": 20.79606056213379,
  "more_data" : {...}
}

Marshmallow doesn't serialize private members so this is as close as I can get -

class ApiSchema(Schema):
    class Meta:
        strict = True

    time = fields.Number()
    id = fields.String()

But I do need the underscores in the output json.

Is there a way to tell Marshmallow to serialize the fields using different names?

Answer

johndodo picture johndodo · Oct 16, 2019

The accepted answer (using attribute) didn't work for me, possibly because:

Note: This should only be used for very specific use cases such as outputting multiple fields for a single attribute. In most cases, you should use data_key instead.

However data_key worked nicely:

class ApiSchema(Schema):
    class Meta:
        strict = True

    _time = fields.Number(data_key="time")
    _id = fields.String(data_key="id")