Allow JSONEncoder to handle passing unsupported dict keys through `.default()` before throwing TypeError
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 36k
- PR 合并指标
- PR 指标待抓取
描述
Feature or enhancement
Proposal:
Encoding a dict to JSON raises TypeError if a key is not one of the simple types natively supported by JSON (bool, None, int, float, str).
However, some other types of objects are "JSON-like" enough that users commonly use them as keys, and it would be handy to be able to dump such dicts to JSON format. For values, this is supported via the encoder's .default() method, but for keys there isn't a current way to accomplish this other than manually processing the dict to convert all such keys before passing it to JSONEncoder. It can't be handled in .default() as a dict doesn't get passed to .default().
Example objects that are not simple types but used as keys (I've used all these myself):
to_encode = {
b"foobar": "bytes key",
pathlib.Path("/tmp"): "Path key",
uuid.uuid4(): "UUID key",
ipaddress.ip_address("127.0.0.1"): "IP address key",
}
Calling json.dumps() on such a dict will raise TypeError: keys must be str, int, float, bool or None, not bytes, even if you try to subclass JSONEncoder and handle a dict's keys in .default().
I have a patch that adds an optional kwarg convert_keys that, when set, causes the encoder to pass such keys through the encoder's .default() method, and only raise an exception if that does not return one of the JSON-supported types. It defaults to off, and skipkeys still takes precedence over the new setting, so existing uses will see no change in behaviour.
I did search for discussions of this, but didn't find anything related, only other proposals like adding a JSON dunder method so any object can control its JSON serialization, which is a different approach. I believe my approach is much more similar to the way values are currently handled, and will therefore be more familiar to users.
Has this already been discussed elsewhere?
This is a minor feature, which does not need previous discussion elsewhere
Links to previous discussion of this feature:
No response
Linked PRs
- gh-117392
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从 Python 的 JSONEncoder 键处理及其现有的 default() 路径入手;该 issue 未指定源文件或测试。查看链接的 PR gh-117392,并确认可选的键转换保留现有行为、遵循 skipkeys,并且仅在转换未产生 JSON 支持的键类型时出错。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- backend
- Issue 类型
- 功能
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 25/100