英文:
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
数据,然后使用map
和Unmarshal
进行处理:
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"])
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论