无法将字符串映射转换为json

Kar*_*lom 2 hash json go redis redigo

我想使用redigo从redis收到的hash中创建一个json :

func showHashtags(c *gin.Context) {
    hashMap, err := redis.StringMap(conn.Do("HGETALL", MyDict))
    if err != nil {
        fmt.Println(err)
    }    
    fmt.Println(hashMap) //works fine and shows the map 

    m := make(map[string]string)
    for k, v := range hashMap {
        m[k] = v
    }

    jmap, _ := json.Marshal(m)
    c.JSON(200, jmap)
}
Run Code Online (Sandbox Code Playgroud)

然而,浏览器的结果是乱码,如:

"eyIgIjoiMiIsIjExX9iq24zYsSAiOiIxIiwiQWxsNFJhbWluICI6IjEiLCJCSUhFICI6IjMiLCJCVFNBUk1ZICI6IjIiLCJDTUJZTiAiOiIxI....
Run Code Online (Sandbox Code Playgroud)

这有什么不对?我该如何解决?

Cer*_*món 7

变量jmap是类型[]byte.正如您在输出中看到的那样,在c.JSON()编组中调用JSON编码器[]byte作为base64编码的字符串.

要解决此问题,请通过将映射直接传递给c.JSON来使用一级JSON编码:

hashMap, err := redis.StringMap(conn.Do("HGETALL", MyDict))
if err != nil {
    // handle error
}    
m := make(map[string]string)
for k, v := range hashMap {
    m[k] = v
}

c.JSON(200, m)
Run Code Online (Sandbox Code Playgroud)

因为hashMapmap[string]string,你可以直接使用它:

hashMap, err := redis.StringMap(conn.Do("HGETALL", MyDict))
if err != nil {
    // handle error
}    
c.JSON(200, hashMap)
Run Code Online (Sandbox Code Playgroud)