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

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

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"]的键和值。

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

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

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

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

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

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"]

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

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

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

And I also paste my Response code as below:

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

答案1

得分: 0

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

  1. json_str, jsonErr := json.Marshal(data)
  2. if json_str != nil {
  3. fmt.Printf("%v", jsonErr)
  4. }
  5. m := make(map[string]interface{})
  6. err := json.Unmarshal([]byte(json_str), &m)
  7. if err != nil {
  8. fmt.Println(err)
  9. fmt.Println("这是ID", m["id"])
  10. }
英文:

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

  1. json_str, jsonErr := json.Marshal(data)
  2. if json_str != nil {
  3. fmt.Printf("%v", jsonErr)
  4. }
  5. m := make(map[string]interface{})
  6. err := json.Unmarshal([]byte(json_str), &m)
  7. if err != nil {
  8. fmt.Println(err)
  9. fmt.Println("This is ID", m["id"])
  10. }

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:

确定