Skip to content

How to serialize (JSON) a type reference? #315

Open
@kkg-else42

Description

@kkg-else42

(I know it's not a cattrs issue.)
I'm looking for a way to JSON-serialize a type-ref inside a attrs-class.
But type-refs aren't supported by json-lib.
See a litte example:

import attrs, cattrs, json

@attrs.mutable
class A:
    my_type: type

@attrs.mutable
class B:
    foo: int

a1=A(my_type=B)

a1u=cattrs.unstructure(a1)

a1uj=json.dumps(a1u)
Traceback (most recent call last):
  File "C:\Python310\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "C:\Python310\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "C:\Python310\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Python310\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:\Python310\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type type is not JSON serializable

Are there any ideas on how to achieve my goal?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions