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

Comments

@MrTravisB
Copy link

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
@agnivade
Copy link
Contributor

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.

@golang golang locked and limited conversation to collaborators Jun 18, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants