You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用redis-py将字典设置为Redis JSON对象时报错如何解决

问题原因

报错的核心是 JSON 标准不允许使用 bytes 类型作为对象的键,redis-py 的 JSON 命令在序列化写入数据前会做类型校验,你定义的字典 d 中包含 b"some" 这个 bytes 类型的键,不符合校验规则因此抛出错误。

解决方案
  • 静态定义字典时直接将 bytes 类型的键改为字符串类型,修改后的可运行代码如下:
import redis
from redis.commands.json.path import Path
from redis import exceptions
from redis.commands.json.decoders import unstring, decode_list

r = redis.Redis()
d = {"hello": "world", "some": "value"}
r.json().set("somekey", Path.rootPath(), d)
  • 如果键是程序动态生成的 bytes 类型,提前调用 decode 方法转为字符串即可:
dynamic_bytes_key = b"some"
d = {"hello": "world", dynamic_bytes_key.decode("utf-8"): "value"}
  • 如果你有存储二进制内容的需求,不要将二进制数据作为字典键使用,可以将二进制内容转成 base64 编码的字符串后作为字典值存储,即可兼容 Redis JSON 的类型要求。

内容的提问来源于stack exchange,提问作者user3533755

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 19:15:04