Closed
Description
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"}
Metadata
Metadata
Assignees
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
mvdan commentedon 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.
rsc commentedon 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 commentedon 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.