ramonhagenaars / jsons

🐍 A Python lib for (de)serializing Python objects to/from JSON
https://jsons.readthedocs.io
MIT License
289 stars 41 forks source link

dicts are serialized wrongly when assigned to an attribute with an 'Any' type #192

Open Gollimnar opened 6 months ago

Gollimnar commented 6 months ago

Class members typed as 'Any' will have their value serialized using default_object_serializer(). This produces wrong results for dict objects. For example:

from typing import Any, Dict
import jsons

# BadClass will fail to serialize properly.
class BadClass:
    key: str
    value: Any # This is the problem.

bc = BadClass()
bc.key = "bad"
bc.value = {"a": "b", "c": "d", "e": "f"}

print(jsons.dumps(bc))

# GoodClass will work as expected.
class GoodClass:
    key: str
    value: Dict[str, Any]

gc = GoodClass()
gc.key = "good"
gc.value = {"a": "b", "c": "d", "e": "f"}

print(jsons.dumps(gc))

The expected result:

{"key": "bad", "value": {"a": "b", "c": "d", "e": "f"}}
{"key": "good", "value": {"a": "b", "c": "d", "e": "f"}}

The actual result:

{"key": "bad", "value": {"clear": {}, "copy": {}, "fromkeys": {}, "get": {}, "items": {}, "keys": {}, "pop": {}, "popitem": {}, "setdefault": {}, "update": {}, "values": {}}}
{"key": "good", "value": {"a": "b", "c": "d", "e": "f"}}

Perhaps Any-types (as well as union types?) should be special cases and infer the serializer from the actual value?