Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include / exclude a struct's field in JSON dynamically?

Tags:

json

struct

go

I have a ‍‍struct Base :

type Base struct {
        Name string `json:"name,omitempty"`
        // ... other fields
}

And two more structs that embed Base:

type First struct {
        Base
        // ... other fields
}

type Second struct {
        Base
        // ... other fields
}

Now I want to Marshal the structs First and Second but with a little difference. I want to include the Name field in First but I don't want to include it in Second.

Or to simplify the question I want to opt in and out a struct's field in its JSON dynamically.

Note: The Name value always has value and I don't want to change it.

like image 384
mehdy Avatar asked Oct 22 '16 13:10

mehdy


1 Answers

You can implement the Marshaler interface for type Second and create a dummy type SecondClone.

type SecondClone Second

func (str Second) MarshalJSON() (byt []byte, err error) {

   var temp SecondClone
   temp = SecondClone(str)
   temp.Base.Name = ""
   return json.Marshal(temp)
}

This will work with no other changes to your code.

And it won't modify the value in Name as it works on a different type / copy.

like image 129
John S Perayil Avatar answered Nov 07 '22 13:11

John S Perayil