Marshaling Struct Print

68 views
Skip to first unread message

Shishir Jakati

unread,
Jun 21, 2019, 10:06:47 AM6/21/19
to golang-nuts
Say I have a struct
type MyStruct struct {
 
string `json:",inline"`
 
int `json:"omitempty"`
}

Is there any way to utilize the JSON tags to omit the empty fields when I call a function like 
fmt.Sprintf("%#v",s)
where s is an instance of my struct?

Ian Lance Taylor

unread,
Jun 21, 2019, 10:12:40 AM6/21/19
to Shishir Jakati, golang-nuts
There is no simple way. You can define a GoString method to print the
struct however you like (https://golang.org/pkg/fmt/#GoStringer), but
you'll have to define such a method for each type for which you want
special handling.

Ian

mlevi...@gmail.com

unread,
Jun 21, 2019, 11:19:10 PM6/21/19
to golang-nuts
Course you could think of something like:

func (ms MyStruct) String() string {
    b, err := json.Marshal(ms)
    if err != nil {
        panic(err)
    }
    return string(b)
}

but this is not really performant, since you're calling the JSON parser for real (however, any empty field marked as "omitempty" in its tag would effectively be omitted).
The only other way to go I can think of right now is to use reflection --> tags, and then choosing what you do according to what you encounter. But again, this is quite greedy (speaking of execution time).
Why don't you just use spew? Course this is greedy as well but at least you don't get to re-invent the wheel.
Maybe if you state your need in a clearer way, we can help you better? :)

Keep GoIng ;)
Reply all
Reply to author
Forward
0 new messages