jsons icon indicating copy to clipboard operation
jsons copied to clipboard

Declaring serializer mapping for a single dump

Open casparjespersen opened this issue 5 years ago • 4 comments

Is it possible declaring a serializer for a single dump command, instead of declaring it globally?

Currently:

jsons.set_serializer(my_datetime_serializer, datetime)
jsons.dump(foo)

Suggested:

jsons.dump(foo, serializers={datetime: my_datetime_serializer})

Motivation: I want to have only a particular dump pass datetimes along without string parsing, since the output should be populated in a MongoDB. However, I do other dump's in the script that should use regular behaviour.

jsons.set_serializer(my_datetime_serializer, datetime)
jsons.dump(foo)
jsons.dump(bar) # this should not have my_datetime_serializer

Obviously I could set serializer before and after, but this appears hacky-hacky, and assumes that I know the previous serializer:

jsons.set_serializer(my_datetime_serializer, datetime)
jsons.dump(foo)
jsons.set_serializer(custom_datetime_serializer, datetime)
jsons.dump(bar) # this should not have my_datetime_serializer

casparjespersen avatar May 28 '19 06:05 casparjespersen

Not tried but I would expect following code to work.

f1 = jsons.JsonSerializable.fork()
f1.set_serializer(my_datetime_serializer, datetime)
jsons.dump(foo, fork_inst=f1)

I did not see it in the documentation. Maybe the documentation could be updated.

ahmetkucuk avatar May 30 '19 20:05 ahmetkucuk

Thank you @ahmetkucuk. That works.

casparjespersen avatar Jun 01 '19 08:06 casparjespersen

Great question Casparjespersen. Even though @ahmetkucuk answered your question correctly, I believe your suggestion deserves consideration. I like the idea of being able to "temporarily" override the (de)serialization behavior of some types.

As for the current solution that Ahmetkucuk rightly mentioned, I'm thinking of deprecating it (to have it removed later). It makes no sense (anymore) that JsonSerializable is to be involved. Rather, I'm thinking of a mere function like jsons.fork().

I am curious about the opinion of you guys on this. 🙂

ramonhagenaars avatar Jun 02 '19 20:06 ramonhagenaars

I did not have a chance to look in detail. In general, it makes sense to me directly calling jsons.fork()

Is there any way of avoiding .copy() in the .fork()?

Instead, maybe we can use a fallback approach: if there is a serializer/deserializer is defined in custom JsonSerializable, use it. Otherwise, use globally defined one?

I think Gson library uses a builder where you can also pass configurations: https://static.javadoc.io/com.google.code.gson/gson/2.8.2/com/google/gson/GsonBuilder.html

In jsons, some configurations cannot be defined in JsonSerializable I guess? e.g. key_transformer

ahmetkucuk avatar Jun 04 '19 19:06 ahmetkucuk