Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Go return struct as JSON in HTTP request

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading