How do I override the JSON encoder used the marshmallow library so that it can serialize a Decimal
field?I think I can do this by overriding json_module
in the base Schema
or Meta
class, but I don't know how:
https://github.com/marshmallow-code/marshmallow/blob/dev/marshmallow/schema.py#L194
I trawled all the docs and read the code, but I'm not a Python native.
If you want to serialize a Decimal
field (and keep the value as a number), you can override the default json module used by Marshmallow in its dumps()
call to use simplejson
instead.
To do this, just add a class Meta
definition to your schema, and specify a json_module
property for this class.
Example:
import simplejson
class MySchema(Schema):
amount = fields.Decimal()
class Meta:
json_module = simplejson
Then, to serialize:
my_schema = MySchema()
my_schema.dumps(my_object)
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