How can I prevent JSON from being unmarshaled into a field of a struct?
from lena@gregtech.eu to golang@programming.dev on 31 Jul 2025 15:54
https://gregtech.eu/post/16712875
from lena@gregtech.eu to golang@programming.dev on 31 Jul 2025 15:54
https://gregtech.eu/post/16712875
Marshaling the field is fine, so using the tag json:“-” won’t work. I could use the UnmarshalJSON method on the struct, but I have no idea how to implement it.
I’d rather not make a duplicate of the struct with that field removed, as it causes quite a bit of code duplication, and it’s pretty chaotic.
#golang
threaded - newest
One option is to use embedded structs:
type UnmarshalStruct struct { Foo string } type MarshalStruct struct { UnmarshalStruct FieldYouDontWantUnmarshaled string }When marshaling, you would marshal
MarshalStruct. BecauseUnmarshalStructis embedded,json.Marshalautomatically includes all the fields fromUnmarshalStruct.When unmarshaling, you would unmarshal
UnmarshalStructand then create a newMarshalStructlike this:var unmarshaled UnmarshalStruct err := json.Unmarshal(&unmarshaled) if err != nil { panic(err) } return MarshalStruct { UnmarshalStruct: unmarshaled }Although, if I may ask: why do you not want a field to be unmarshaled? You could always just set it back to the zero value after unmarshaling, which is a lot easier of a solution.