You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Json encode from __repr__, __str__ or __serialize__ when available #114285
When I need to json encode a new object or an Enum , I need to either extend str, or build a json decoder to make it compatible with the default json encoder.
When using third parties lib, it might create some difficulties as implementing string is not an option, and the dumps method is not reachable.
If I wanted to do that in java, I would implement in my class a serialize method that would be called by json serializer.
Would it be possible, in the encoder, to allow the usage of either a serialize(self) method, or to directly use repr or str when the object after all other option failed.
Activity
sobolevn commentedon Jan 19, 2024
Please, start a new discussion on https://discuss.python.org/c/ideas/6
But, I guess this was already discussed.
You can do that if you want:
Decoderif you want__json_encode__and__json_decode__magic method that you can define on any objects (or even monkey-patch them to existing ones)I will close this for now, you can follow up this issue with the discussion link! 👍
ronaldoussoren commentedon Jan 19, 2024
This is a duplicate of #71549. That issue proposes a different method (
__json__instead of__serialize__).The other issue also doesn't propose a fallback to
__repr__or__str__, but IMHO that would be a bug magnet.