How to recursively enrich json object with custom field using python jsons

96 Views Asked by At

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.

1

There are 1 best solutions below

0
Krever On

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)