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?
Introduction. Marshmallow, stylized as “marshmallow”, is an object-relational mapping library which is used to convert objects to and from Python data types. It is often used alongside SQLAlchemy, an ORM that maps database schemas to Python objects.
Schemas can be nested to represent relationships between objects (e.g. foreign key relationships). For example, a Blog may have an author represented by a User object. Use a Nested field to represent the relationship, passing in a nested schema.
Deserialization is the opposite of serialization. To serialize, we converted data from Python to JSON. To deserialize, we are converting JSON data to SQLAlchemy objects. When deserializing objects from the SQLite database, Marshmallow automatically converts the serialized data to a Python object.
marshmallow is an ORM/ODM/framework-agnostic library for converting complex datatypes, such as objects, to and from native Python datatypes. In short, marshmallow schemas can be used to: Validate input data. Deserialize input data to app-level objects.
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")
https://marshmallow.readthedocs.io/en/2.x-line/quickstart.html#specifying-attribute-names
Even though the docs are for version 2, this seems to still work as of 3.5.1. The stable version 3 docs will not have this example.
class ApiSchema(Schema):
class Meta:
strict = True
_time = fields.Number(attribute="time")
_id = fields.String(attribute="id")
The answer's well documented in Marshmallows api reference.
I need to use dump_to
:
class ApiSchema(Schema):
class Meta:
strict = True
time = fields.Number(dump_to='_time')
id = fields.String(dump_to='_id')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With