英文:
how to Unmarshal json in golang
问题
我有一个 JSON 数据:
{"code":200,
"msg":"success",
"data":{"url":"https:\/\/mp.weixin.qq.com\/cgi-bin\/showqrcode?ticket=gQHQ7jwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyX3pqS0pMZlA4a1AxbEJkemhvMVoAAgQ5TGNYAwQsAQAA"}}
我定义了一个结构体:
type Result struct {
code int
msg string `json:"msg"`
data map[string]interface{} `json:"data"`
}
对于这段代码:
var res Result
json.Unmarshal(body, &res)
fmt.Println(res)
输出结果是:{0 map[]}
我想要获取 data
中的 url
,该如何获取呢?
英文:
I have a json:
{"code":200,
"msg":"success",
"data":{"url":"https:\/\/mp.weixin.qq.com\/cgi-bin\/showqrcode?ticket=gQHQ7jwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyX3pqS0pMZlA4a1AxbEJkemhvMVoAAgQ5TGNYAwQsAQAA"}}
and i define a struct :
type Result struct {
code int
msg string `json:"msg"`
data map[string]interface{} `json:"data"`
}
for this code:
var res Result
json.Unmarshal(body, &res)
fmt.Println(res)
the output is: {0 map[]}
i want to get url
in data
, how to get it?
答案1
得分: 4
你应该通过将字段(Code
、Msg
、Data
)的首字母大写来导出Result
的字段(code
、msg
、data
),以便访问(设置/获取)它们:
package main
import (
"encoding/json"
"fmt"
)
type Result struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data map[string]interface{} `json:"data"`
}
func main() {
str := `{"code":200,"msg":"success","data":{"url":"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQHQ7jwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyX3pqS0pMZlA4a1AxbEJkemhvMVoAAgQ5TGNYAwQsAQAA"}}`
var res Result
err := json.Unmarshal([]byte(str), &res)
fmt.Println(err)
fmt.Println(res)
}
在https://play.golang.org/p/23ah8e_hCa上运行代码。
相关问题:https://stackoverflow.com/questions/24837432/golang-capitals-in-struct-fields
英文:
You should export fields (code
, msg
, data
) for Result
by capitalizing the first letter of fields (Code
, Msg
, Data
) to access (set/get) them:
package main
import (
"encoding/json"
"fmt"
)
type Result struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data map[string]interface{} `json:"data"`
}
func main() {
str := `{"code":200,"msg":"success","data":{"url":"https:\/\/mp.weixin.qq.com\/cgi-bin\/showqrcode?ticket=gQHQ7jwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyX3pqS0pMZlA4a1AxbEJkemhvMVoAAgQ5TGNYAwQsAQAA"}}`
var res Result
err := json.Unmarshal([]byte(str), &res)
fmt.Println(err)
fmt.Println(res)
}
Play the code on https://play.golang.org/p/23ah8e_hCa
Related question: https://stackoverflow.com/questions/24837432/golang-capitals-in-struct-fields
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论