Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set set JSON encoder in marshmallow?

Tags:

python

json

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.

like image 243
Petrus Theron Avatar asked Mar 09 '16 16:03

Petrus Theron


1 Answers

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)
like image 76
Chris Hickman Avatar answered Oct 07 '22 00:10

Chris Hickman