Reputation: 4502
Let's say I have the following types:
type Inner struct {
Field1 string `json:"field1"`
Field2 string `json:"field2"`
}
type Outer struct {
Inner
Field2 string `json:"-"`
}
What I am trying to accomplish with this is to allow having a type (Outer
) that includes all of the fields in an embedded type (Inner
), but overrides one of the fields to not be marshalled in JSON. This does not work, and calling json.Marshal(Outer{})
returns:
{"field1":"","field2":""}
Is there any way to do this in Go that will instead return this?
{"field1":""}
Upvotes: 3
Views: 2795
Reputation: 18280
You can do something like this (the key is that the output tag has the same name):
type Inner struct {
Field1 string `json:"field1"`
Field2 string `json:"field2"`
}
type Outer struct {
Inner
NameDoesNotMatter string `json:"field2,omitempty"`
}
func main() {
j, err := json.Marshal(Outer{})
if err != nil {
panic(err)
}
fmt.Printf("1: %s\n", j)
v := Inner{
Field1: "foo",
Field2: "bar",
}
j, err = json.Marshal(Outer{Inner: v})
if err != nil {
panic(err)
}
fmt.Printf("2: %s\n", j)
}
Output:
1: {"field1":""}
2: {"field1":"foo"}
I found this article very useful when looking into how to manipulate JSON output using struct composition.
Upvotes: 6