0

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.

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

1 Answer 1

6

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.