WARNING: THIS SITE IS A MIRROR OF GITHUB.COM / IT CANNOT LOGIN OR REGISTER ACCOUNTS / THE CONTENTS ARE PROVIDED AS-IS / THIS SITE ASSUMES NO RESPONSIBILITY FOR ANY DISPLAYED CONTENT OR LINKS / IF YOU FOUND SOMETHING MAY NOT GOOD FOR EVERYONE, CONTACT ADMIN AT ilovescratch@foxmail.com
Skip to content

Generic types cannot be deserialized #194

@SusanneLindgren

Description

@SusanneLindgren

If a value has type dict, it can be deserialized, but not if it has a more specific type like dict[str, str]; then you get an exception:

jsons.exceptions.DeserializationError: Could not deserialize value "{'foo': 'bar'}" into "dict". isinstance() argument 2 cannot be a parameterized generic

Example code:

import jsons
from dataclasses import dataclass

@dataclass
class Test:
    value: dict[str, str]  # but "dict" works

t = Test({"foo": "bar"})
dumped = jsons.dump(t)
reloaded = jsons.load(dumped, Test)
print(reloaded.value)

Suggested fix: change default_union_deserializer in jsons/deserializers/default_union.py from return load(obj, sub_type, **kwargs) to

            try:
                origin_type = sub_type.__origin__
            except AttributeError:
                origin_type = sub_type
            return load(obj, origin_type, **kwargs)

A similar fix would have to be done for lists.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions