1

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 MyFoos and so the serializer must work on all levels.

Krever
  • 1,371
  • 1
  • 13
  • 32
  • Out of more than 50 existing questions tagged [tag:python-jsons], this was the **only one** that was actually about the `jsons` library, which is what the tag is presumably intended for. I retagged all the others. – Karl Knechtel Apr 01 '23 at 08:15

1 Answers1

0

I managed to solve it. The trick was to use jsons.default_object_serializer

def adjust(obj):
    if isinstance(obj, MyFoo):
        json = jsons.default_object_serializer(obj)
        json['foo'] = "bar"
        return json
jsons.set_serializer(lambda obj, **_: adjust(obj), MyFoo)
json = jsons.dump(data, ensure_ascii=True)
Krever
  • 1,371
  • 1
  • 13
  • 32