-1

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:}]
TestingInProd
  • 349
  • 10
  • 26

1 Answers1

3

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

Grzegorz Żur
  • 47,257
  • 14
  • 109
  • 105
  • thanks..you are right – TestingInProd Oct 29 '16 at 23:26
  • Just a follow up question. I got the output as below when I added Type and Paylod {Id:4787366250 Type:IssueCommentEvent Payload:{Size:0}} {Id:4787366249 Type:PushEvent Payload:{Size:1}} Is there way to filter Type in the Struct itself ? What I meant was, can I do the below type events struct { Id string `json:"id"` Type string `json:"type":"PushEvent"` Payload eventPayload `json:"payload"` } Checking whether type is PushEvent – TestingInProd Oct 29 '16 at 23:45