how to Unmarshal json in golang

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

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

你应该通过将字段(CodeMsgData)的首字母大写来导出Result的字段(codemsgdata),以便访问(设置/获取)它们:

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

huangapple
  • 本文由 发表于 2016年12月28日 13:25:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/41355847.html
匿名

发表评论

匿名网友

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

确定