Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
MrTravisB opened this issue Jun 18, 2019 · 1 comment
Closed

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

MrTravisB opened this issue Jun 18, 2019 · 1 comment
Labels
Milestone

Comments

@MrTravisB
Copy link

@MrTravisB MrTravisB commented Jun 18, 2019

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()
}
@gopherbot gopherbot added this to the Proposal milestone Jun 18, 2019
@gopherbot gopherbot added the Proposal label Jun 18, 2019
@agnivade

This comment has been minimized.

Copy link
Contributor

@agnivade agnivade commented Jun 19, 2019

Duplicate of #11939.

And I guess you already knew, but just wanted to put it out there - if you change Name to a pointer like

Name *Name `json:"name,omitempty"`

"name": {} goes away.

@agnivade agnivade closed this Jun 19, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
3 participants
You can’t perform that action at this time.