this post was submitted on 31 Jul 2025
7 points (100.0% liked)

Golang

2610 readers
13 users here now

This is a community dedicated to the go programming language.

Useful Links:

Rules:

founded 2 years ago
MODERATORS
 

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.

top 3 comments
sorted by: hot top controversial new old
[–] pivot_root@lemmy.world 2 points 5 months ago

One option is to use embedded structs:

type UnmarshalStruct struct {
    Foo string
}

type MarshalStruct struct {
    UnmarshalStruct
    FieldYouDontWantUnmarshaled string
}

When marshaling, you would marshal MarshalStruct. Because UnmarshalStruct is embedded, json.Marshal automatically includes all the fields from UnmarshalStruct.

When unmarshaling, you would unmarshal UnmarshalStruct and then create a new MarshalStruct like 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.

[–] gxlin@mas.to 1 points 5 months ago* (last edited 5 months ago) (1 children)

@lena (I just realized you had use UnmarshalJSON(). Please ignore my previous posts 🙈 )

> 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.

Such duplication is good to involve from my perspective. It is okay, and maybe common, for data to have different presentation between codebase and exposed APIs.

[–] lena 2 points 5 months ago

Yeah, I decided to just go with that approach to keep things separate. Thanks for the help!