英文:
Json parsing in go
问题
我正在尝试解析这个网址中的JSON数据。我的代码如下,但输出结果与预期不符。我想要提取pushevent中payload中的id和url。我该如何做?谢谢。
type events struct {
id string `json:"id"`
}
func pullUrlFromGit(urlHolder chan string){
client := &http.Client{}
resp, _ := client.Get("https://api.github.com/events")
defer resp.Body.Close()
body,_ := ioutil.ReadAll(resp.Body)
var gtevents []events
json.Unmarshal(body,>events)
log.Printf("%+v",gtevents)
}
我得到的输出结果如下:
[{id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:}]
英文:
I am trying to parse json in this url. My code is as below, but the output is not as expected. I want to extract id, url inside payload only for pushevent. How do i do that . Thanks
type events struct {
id string `json:"id"`
}
func pullUrlFromGit(urlHolder chan string){
client := &http.Client{}
resp, _ := client.Get("https://api.github.com/events")
defer resp.Body.Close()
body,_ := ioutil.ReadAll(resp.Body)
var gtevents []events
json.Unmarshal(body,&gtevents)
log.Printf("%+v",gtevents)
}
The output i am getting is as below.
[{id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:} {id:}]
答案1
得分: 3
使id
字段大写
type events struct {
Id string `json:"id"`
}
Go的json库使用反射来访问结构体的字段。反射只允许修改导出的字段。因此,您需要通过将第一个字母大写来导出该字段。
参见反射法则
英文:
Make id
field uppercase
type events struct {
Id string `json:"id"`
}
Go json library uses reflection to access fields of structures. Reflection allows only exported fields to be modified. Therefore you need to make that field exported by making the first letter uppercase.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论