Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Thanks to encoding hooks, why not supporting arbitrary objects as dict keys? #568

Closed
shangoue opened this issue Oct 16, 2023 · 1 comment · Fixed by #602
Closed

Thanks to encoding hooks, why not supporting arbitrary objects as dict keys? #568

shangoue opened this issue Oct 16, 2023 · 1 comment · Fixed by #602

Comments

@shangoue
Copy link

shangoue commented Oct 16, 2023

Description

First, thanks for this great library!
I would like to serialize a dict whose keys are instances of a class coming from another library. I am already able to serialize these objects using enc_hook parameter to convert them as strings. But if these objects are converted to strings, why we cannot use them as keys for json dict ?

Here is a minimalist example:

from typing import Any, Dict, Type
import msgspec

class OpCode:
    pass

def enc_opcode(obj: Any):
    if isinstance(obj, OpCode):
        return "opcode"
    raise NotImplementedError(f"Cannot serialize {type(obj)}")

data = {}
data[OpCode] = 1
msgspec.json.encode(data, enc_hook=enc_opcode)
@jcrist
Copy link
Owner

jcrist commented Nov 7, 2023

Thanks for opening this; you've found a bug! This currently works correctly for msgspec.msgpack.decode and msgspec.convert, but fails for msgspec.json.decode. Will fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants