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

How do I lowercase a nested struct name when using json.marshal?

I’m exposing a REST endpoint with some data. It’s a struct, say:

type status struct {
    Config struct {
        Allow   bool `json:"allow"`
        Expired bool `json:"expired"`
    }
    Database struct {
        Healthy          bool   `json:"healthy"`
        WaitCount        int64  `json:"wait_count"`
    }
}

I’m using the json tag to denote how a struct field should look when calling the endpoint. Using the above, I’m getting the following payload as response:

{
    "Config": {
        "allow": false,
        "expired": false,
    },
    "Database": {
        "healthy": true,
        "wait_count": 1,
    },
}

I’d like for Config and Database to be lowercase, meaning config and database. However, changing them to that in the Go code means the "encoding/json" package cannot "see" them as they aren’t exported outside of the package scope.

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

How do I lowercase the nested struct’s in the json response payload?

>Solution :

The nested struct is a field in the containing struct. Add a field tags as you did with the other fields:

type status struct {
    Config struct {
        Allow   bool `json:"allow"`
        Expired bool `json:"expired"`
    } `json:"config"` // <-- add tag here ...
    Database struct {
        Healthy          bool   `json:"healthy"`
        WaitCount        int64  `json:"wait_count"`
    } `json:"database"` // <-- ... and here
}
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