Q:

JSON marshalling/unmarshalling same struct to different JSON format in go?

I have a struct that I'd like to Marshal into JSON differently depending on the context.
For example, sometimes I want to marshal like this:
    type MyStruct struct {
        Nickname       string `json:"nickname"`
        EmailAddress   string `json:"email_address"`
        PhoneNumber    string `json:"-"`
        MailingAddress string `json:"-"`
    }

And sometimes I want to marshal like this:
    type MyStruct struct {
        Nickname       string `json:"nickname"`
        EmailAddress   string `json:"email_address"`
        PhoneNumber    string `json:"phone_number"`
        MailingAddress string `json:"mailing_address"`
    }

Is there a simple way to do this without:

Making 2 separate structs.
Writing a custom marshaller.
Temporarily removing the string values for PhoneNumber and MailingAddress (with an omitempty on the tag), marshaling and then adding them back.

If only there was a way to:

Specify 2 sets of tags and tell the marshaler which ones to use.
Dynamically change the tags at runtime.

A:

I know you explicitly mention "without writing a custom marshaler", but in case someone sees this and thinks it should be avoided because of complexity, a custom marshaler to do what you want to do is really simple:
type MyStruct struct {
    Nickname       string `json:"nickname"`
    EmailAddress   string `json:"email_address"`
    PhoneNumber    string `json:"phone_number"`
    MailingAddress string `json:"mailing_address"`
    all            bool
}

func (ms MyStruct) MarshalJSON() ([]byte, error) {
    m := map[string]interface{}{} // ideally use make with the right capacity
    m["nickname"] = ms.Nickname
    m["email_address"] = ms.EmailAddress
    if ms.all {
        m["phone_number"] = ms.PhoneNumber
        m["mailing_address"] = ms.MailingAddress
    }
    return json.Marshal(m)
}

If the all field should be set by an external package, then a method could be defined on the struct, or the field could be made public (wouldn't affect the JSON since it is encoded via the custom marshaler).
Runnable example on the playground: http://play.golang.org/p/1N_iBzvuW4

