0

as first time Quart user, I struggle defining json encoder / decoder. I have nested objects like this:

class ObjA:
    def __init__(self, name, color):
        self.name = name
        self.__color = color

class Color:
    def __init__(self, t):
        self.t = t

Is it possible to define encoder/decoder foreach Class and let quart handle the rest ?

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
Roby
  • 2,011
  • 4
  • 28
  • 55
  • In my answer I've assumed you just want to use the `jsonify` function to return json. If you want to accept json, or something else (a reason to need a decoder) could you say what the use case is? – pgjones Jun 05 '18 at 20:40

1 Answers1

2

Assuming you want to use the jsonify function, you can do this by defining a custom JSONEncoder as so,

from quart.json import JSONEncoder

class CustomJSONEncoder(JSONEncoder):

    def default(self, obj):
        if isinstance(obj, Color):
            return obj.t
        elif isinstance(obj, ObjA):
            return {
                'name': obj.name,
                '_color': self.default(obj._color),
            }
        else:
            return JSONEncoder.default(self, obj)

app = Quart(__name__)
app.json_encoder = CustomJSONEncoder

Note I've changed the __color variable to _color to avoid issues with name mangling.

pgjones
  • 6,044
  • 1
  • 14
  • 12