如何在golang中解组json

时间:2016-12-28 05:25:32

标签: json go

我有一个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[]}

我想在url中获得data,如何获得它?

1 个答案:

答案 0 :(得分:2)

您应该通过大写字母的第一个字母(codemsg来导出data的字段ResultCodeMsg) },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

上播放代码

相关问题:Golang - Capitals in struct fields