TheLion TheLion - 1 month ago 7
JSON Question

Json parsing in go

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:}]

Answer

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

Comments