pythonquart

Quart JSON encoding


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 ?


Solution

  • 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.