0

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?

2
  • 1
    please read this document: yourbasic.org/golang/public-private to know more about public and private variables, it's mistake that happens for all of us Commented Jan 18, 2023 at 10:31
  • 1
    Do not post images of text. Commented Jan 18, 2023 at 11:46

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Please add some information on using JSON tags in Go. By exporting the fields they are indeed marshalled, but they will not be marshalled according to JSON conventions (all lowercase + snake case).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.