-
Notifications
You must be signed in to change notification settings - Fork 18.7k
Closed
Labels
Milestone
Description
It would be nice to be able to omit objects from encoding that are of some custom type. For instance
type Name struct {
First string `json:"first,omitempty"`
Last string `json:"last,omitempty"`
}
type Person struct {
Name Name `json:"name,omitempty"`
Age int `json:"age"`
}
p := Person{
Age: 42,
}
b, _ := json.Marshal(p)
fmt.Println(string(b))
Ideally that would print
{"age":42}
but instead it prints
{"name":{},"age":42}
What would be nice would be to have an interface, json.Empty, which could be used to determine if the value is empty or not.
type Empty interface {
IsEmpty() bool
}
func (n Name) IsEmpty() bool {
return n.First == "" && n.Last == ""
}
The check for this could then just be another case added to json.isEmptyValue()
if emp, ok := v.Interface().(Empty); ok {
return emp.IsEmpty()
}
networkimprov