Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang - Override JSON tag of embedded field

Tags:

json

struct

go

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":""}
like image 294
Jordan Avatar asked Jan 18 '26 23:01

Jordan


1 Answers

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.

like image 96
Brits Avatar answered Jan 20 '26 22:01

Brits