在Go语言中进行JSON解析。

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

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,&gtevents)

    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.

See Laws of Reflection

huangapple
  • 本文由 发表于 2016年10月30日 06:05:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/40324142.html
匿名

发表评论

匿名网友

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

确定