Home > Blockchain >  Go return struct as JSON in HTTP request
Go return struct as JSON in HTTP request

Time:01-19

I've defined the following struct in Go:

type repoStars struct { name string owner string stars int }

And I've created an array repoItems := []repoStars{} which has multiple items of the struct above.

This is how repoItems looks like:

enter image description here

I'm trying to return those items as a JSON response:

    w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(repoItems)

And it seems empty

enter image description here

What am I doing wrong here?

CodePudding user response:

If the struct fields start with a lower case letter it means unexported. All unexported fields won't be serialised by the encoder.

Change it to capital first letter.

type repoStars struct {
    Name string
    Owner string
    Stars int
}
  •  Tags:  
  • go
  • Related