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 an option `omitempty` to json.Encoder #19763

Closed
mkideal opened this issue Mar 29, 2017 · 3 comments
Closed

proposal: encoding/json: add an option `omitempty` to json.Encoder #19763

mkideal opened this issue Mar 29, 2017 · 3 comments

Comments

@mkideal
Copy link

@mkideal mkideal commented Mar 29, 2017

Now, encoding/json should omit empty value if json tag contains omitempty:

type T struct {
	F1 string `json:",omitempty"`
	F2 string `json:",omitempty"`
	F3 string `json:",omitempty"`
	F4 string `json:",omitempty"`
	F5 string `json:",omitempty"`
}

But this is too annoying if many fields should omit empty value.

Can we add an option omitempty to json.Encoder?, e.g.

package main

import "os"
import "encoding/json"

type T struct {
	F1 string
	F2 string
	F3 string
	F4 string
	F5 string
}

func main() {
	t := T{F1:"f1"}
	enc := json.NewEncoder(os.Stdout)
	enc.SetOmitEmpty(true)
	enc.Encode(t)
}
// Output:
// {"F1":"f1"}
@mvdan

This comment has been minimized.

Copy link
Member

@mvdan mvdan commented Mar 29, 2017

Another way to do the same thing seems a bit overkill. How often do you want to omit every single empty field, and there are so many of them?

Remember that there are plenty of third-party json encoders out there. IMO encoding/json should stay simple.

@mvdan mvdan added the Proposal label Mar 29, 2017
@mvdan mvdan added this to the Proposal milestone Mar 29, 2017
@rsc

This comment has been minimized.

Copy link
Contributor

@rsc rsc commented Apr 3, 2017

The biggest question seems to be whether package P generating json of package Q's data structures should be able to change the way package Q's data structures encode. If different packages using Q's data disagree about whether to omitempty, it seems like that might lead to confusion.

That's a big consequence for the convenience of saving a few characters.

@rsc

This comment has been minimized.

Copy link
Contributor

@rsc rsc commented Jun 12, 2017

It still doesn't seem like it should be a global option (instead of per-field or per-type), and no one replied to that.

@rsc rsc closed this Jun 12, 2017
@golang golang locked and limited conversation to collaborators Jun 12, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
4 participants
You can’t perform that action at this time.