Search code examples
jsongostructgo-structtag

How do I change the JSON tag within a Go struct?


I have a structure that looks like this

type MediaFile struct {
    ID                   string    `json:"id"`            
    Secret               string    `json:"-"`
    Title                string    `json:"title"`
}

I want to be able to change the script tag for Secret into json:"secret" when a condition is satisfied.

The struct MediaFile has been referenced a lot within other parts of the code, so using a different Struct with a different name isn't feasible.

I tried to use pointers like follows. Note that I have removed the definition of struct Mediafile as seen before in the following example.

type AlterMediaFile struct {
    ID                   string    `json:"id"`            
    Secret               string    `json:"secret"`
    Title                string    `json:"title"`
}

type MediaFile struct {
    *AlterMediaFile
}

But it resulted in me receiving a lot of promoted field errors since it's AlterMediaFile is basically just a nested class of MediaFile in this case.

So, is there any simple way for me to be able to alter the 'Secret' script tag from json:"-" to json:"secret" ?


Solution

  • You can not alter the 'Secret' script tag from json:"-" to json:"secret" at runtime.

    However, you can use the omitempty option, json:"secret,omitempty", to specify that the field should be omitted from the encoding if the field has an empty value (in this case, an empty string).

    When your condition is not satisfied, you can just simply set the Secret field to an empty string (this can be done with your database) and it will not show up in the json data.