I have a struct like this:
type MyStruct struct {
Name string `json:"name"`
Age int `json:"age"`
Email string `json:"email"`
}
Then I have some value (could be default, which means I do not need to update this value) to feed in as HTTP request data. I noticed the generated JSON body will always contains all three fields (name
, age
and email
), even if I don't need to update all of them. Like this:
{
"name":"Kevin",
"age":10,
"email":""
}
Is there a way to Marshal so that the JSON body contains not all fields with the same struct? Example:
{
"name":"kevin"
}
You want to use the omitempty
option
type MyStruct struct {
Name string `json:"name,omitempty"`
Age int `json:"age"`
Email string `json:"email,omitempty"`
}
If you want Age
to be optional as well you have to use a pointer, since the zero value of an int
isn't really "empty"
type MyStruct struct {
Name string `json:"name,omitempty"`
Age *int `json:"age,omitempty"`
Email string `json:"email,omitempty"`
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With