I would like to print dict
with tuple[str]
as a descendant element.JSON does not allow tuple[str]
as the key, so naturally, an error occurred when I ran it as it was.
TypeError: keys must be str, int, float, boolean or None, not tuple
So we created a function that converts keys to str
.For example,
def key_converter(key:tuple[str]):
return f "THIS_IS_A_TUPLE_OF_STRS: {key}"
I would like to do json.dump
using this.
dump(default=key_converter)
Same error.
To implement json.encoder._make_iterencode._iterencode_dict
if isinstance(key,str):
pass
# JavaScript is weakly typed for these, so it makes sense to
# allso allow them. Many encoders seeem to do something like this.
elif...
However, we have verified that the default
given by the user is not used for key conversion but only for value conversion.
dump(default=dict_key_converter)
Same error.
where dict_key_converter
is the 引If the argument is dict
, apply key_converter
to each key に function.
If you look in json.encoder._make_iterencode
, you can also see that isinstance(o,dict)
is called when isinstance(o,dict)
is true, and that _default
is not called.
I don't think it's very wise to write recursive data structures (which I leave to the json
module, but overlap with that).
dict
but is not a subclass of dict
I think it's possible if you wrap it up and transfer the functions you need, but I think it's possible to increase the number of meaningless codes and sacrifice the scalability of other parts.Also, I am currently using defaultdict
, so I have a lot of trouble wrapping it up.
dict
For JSONization, {(a,b):c}
should have been {a:{b:c}}
.This time, we can use the constraints of a, b, and c, so there is no problem if we just encode them.However, in order to distinguish between them, it seems that another twist is needed when decoding.
json
Adding its own featuresGiven the research on the first method you tried, the code modification itself has a policy.
wrap/unwrap
method is sufficient for this application in combination with b.{(a,b):c}
and {a:{b:c}}
are mixed and must be distinguished during encoding.
I'm not sure if we understand each other, but wouldn't it be better to convert the arguments first?
json.dumps({str(k):v fork, vinobj.items()})
613 GDB gets version error when attempting to debug with the Presense SDK (IDE)
916 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
582 PHP ssh2_scp_send fails to send files as intended
573 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
© 2024 OneMinuteCode. All rights reserved.