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

使用Go 1.19与go-rejson库,Redis JSONGet结果转Map遇阻

解决go-rejson库JSONGet返回值转map的问题

针对使用github.com/nitishm/go-rejson/v4库时,JSONGet返回的interface{}转map的问题,提供两种可行方案:

方案1:调用时直接指定目标map类型(推荐)

调用JSONGet时,直接传入map类型的指针作为参数,库会自动将Redis返回的JSON解析到目标变量中:

import (
    "context"
    "github.com/nitishm/go-rejson/v4"
    "github.com/go-redis/redis/v8"
)

func main() {
    ctx := context.Background()
    rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
    jsonClient := rejson.NewReJSONClientFromGoRedisClient(rdb)

    var targetMap map[string]interface{}
    // 第三个参数为JSONPath,"."表示取整个JSON对象
    err := jsonClient.JSONGet(ctx, "your-redis-key", ".", &targetMap)
    if err != nil {
        // 处理错误逻辑
        panic(err)
    }
    // 直接使用targetMap
}

方案2:对已获取的interface{}返回值进行转换

如果已经拿到了interface{}类型的返回值res,可按以下方式处理:

直接类型断言

如果Redis中存储的是JSON对象,res的实际类型就是map[string]interface{},可直接断言:

res, err := jsonClient.JSONGet(ctx, "your-redis-key", ".")
if err != nil {
    panic(err)
}

resultMap, ok := res.(map[string]interface{})
if !ok {
    // 转换失败,说明返回值不是JSON对象(比如是数组、字符串等),需针对性处理
    panic("返回值不是JSON对象类型")
}
// 使用resultMap

序列化兜底(适用于复杂嵌套或断言失败场景)

若直接断言失败,可先将res序列化为JSON字节,再反序列化为map:

import "encoding/json"

// ...

res, err := jsonClient.JSONGet(ctx, "your-redis-key", ".")
if err != nil {
    panic(err)
}

jsonBytes, err := json.Marshal(res)
if err != nil {
    panic(err)
}

var resultMap map[string]interface{}
err = json.Unmarshal(jsonBytes, &resultMap)
if err != nil {
    panic(err)
}
// 使用resultMap

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 12:36:24