How to get value of interface {} in Go? (interface conversion: interface {} is Resp, not map[string]interface {})

huangapple go评论78阅读模式
英文:

How to get value of interface {} in Go? (interface conversion: interface {} is Resp, not map[string]interface {})

问题

根据这个问题和Go代码在Go中将QueryRow扫描到现有的map[string]interface{},我正在尝试获取data["id"]的键和值。

func Login() func(c *lmhttp.Context, code int, data interface{}) (int, interface{}) {
    return func(c *lmhttp.Context, code int, data interface{}) (int, interface{}) {
        map_data := data.(map[string]interface{})
        fmt.Print(map_data, map_data["id"])
    }
}

但是我总是得到以下错误,请给予任何建议,非常感谢。

interface conversion: interface {} is LoginResp, not map[string]interface {}

我还贴出了我的Response代码如下:

func (c *Context) Response(data interface{}) {
    c.result(http.StatusOK, data)
}
英文:

According to this question and the Go code scan a QueryRow to existing map[string]interface{} in Go, I am trying to get key and value of data["id"]

func Login() func(c *lmhttp.Context, code int, data interface{}) (int, interface{}) {
    return func(c *lmhttp.Context, code int, data interface{}) (int, interface{}) {
	map_data := data.(map[string]interface{})
	fmt.Print(map_data, map_data["id"])
  }
}

but I always got error as below,thanks so much for any advice.

interface conversion: interface {} is LoginResp, not map[string]interface {}

And I also paste my Response code as below:

func (c *Context) Response(data interface{}) {
	c.result(http.StatusOK, data)
}

答案1

得分: 0

最后,我通过以下代码获取到了值,使用Marshal获取JSON数据,然后使用mapUnmarshal进行处理:

json_str, jsonErr := json.Marshal(data)
if json_str != nil {
	fmt.Printf("%v", jsonErr)
}
m := make(map[string]interface{})
err := json.Unmarshal([]byte(json_str), &m)
if err != nil {
	fmt.Println(err)
    fmt.Println("这是ID", m["id"])
}
英文:

Finally, I get value by the below code, use Marshal to get JSON data, then map and Unmarshal it,

json_str, jsonErr := json.Marshal(data)
if json_str != nil {
	fmt.Printf("%v", jsonErr)
}
m := make(map[string]interface{})
err := json.Unmarshal([]byte(json_str), &m)
if err != nil {
	fmt.Println(err)
    fmt.Println("This is ID", m["id"])
}
        

huangapple
  • 本文由 发表于 2023年2月11日 14:45:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75418547.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定