Skip to content

proposal: encoding/json: add interface for omitempty #32675

@MrTravisB

Description

@MrTravisB

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()
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions