I'm using jsons library and would like to add a custom serializer that for a given type adds a certain field.
Naive example:
def adjust(obj):
if isinstance(obj, MyFoo):
json = jsons.dump(obj)
json['foo'] = "bar"
return json
jsons.set_serializer(lambda obj, **_: adjust(obj), MyFoo)
json = jsons.dump(data, ensure_ascii=True)
This doesn't work because it goes into infinite recursion. I tried playing with forks but couldn't make it work.
What is important, MyFoo
might appear inside other MyFoo
s and so the serializer must work on all levels.