Skip to content

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

Closed
@mkideal

Description

@mkideal

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"}

Activity

mvdan

mvdan commented on Mar 29, 2017

@mvdan
Member

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.

added this to the Proposal milestone on Mar 29, 2017
rsc

rsc commented on Apr 3, 2017

@rsc
Contributor

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

rsc commented on Jun 12, 2017

@rsc
Contributor

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.

locked and limited conversation to collaborators on Jun 12, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @rsc@mvdan@gopherbot@mkideal

        Issue actions

          proposal: encoding/json: add an option `omitempty` to json.Encoder · Issue #19763 · golang/go