Skip to content

encoding/json: fix using omitempty in combination with MarshalJSON #53425

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

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion src/encoding/json/encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -746,18 +746,39 @@ FieldLoop:
fv = fv.Field(i)
}

// fast path omitEmpty
if f.omitEmpty && isEmptyValue(fv) {
continue
}
omitEmptyResetLocation := e.Len()

e.WriteByte(next)
next = ','
if opts.escapeHTML {
e.WriteString(f.nameEscHTML)
} else {
e.WriteString(f.nameNonEsc)
}
opts.quoted = f.quoted

startLen := e.Len()
f.encoder(e, fv, opts)
newLen := e.Len()

if f.omitEmpty && (newLen-startLen) <= 5 {
// using `Next` and `bytes.NewBuffer` we can modify the end of the
// underlying slice efficiently (without doing any copying)
fullBuf := e.Next(newLen) // extract underlying slice from buffer
switch string(fullBuf[startLen:newLen]) {
case "false", "0", "\"\"", "null", "[]":
// reconstruct buffer without zero value
e.Buffer = *bytes.NewBuffer(fullBuf[:omitEmptyResetLocation])
continue
default:
// reconstruct original buffer
e.Buffer = *bytes.NewBuffer(fullBuf)
}
}
next = ','
}
if next == '{' {
e.WriteString("{}")
Expand Down
16 changes: 13 additions & 3 deletions src/encoding/json/encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ import (
"unicode"
)

type NullMarshal int

func (NullMarshal) MarshalJSON() ([]byte, error) {
return []byte(`null`), nil
}

type Optionals struct {
Sr string `json:"sr"`
So string `json:"so,omitempty"`
Expand All @@ -42,6 +48,9 @@ type Optionals struct {

Str struct{} `json:"str"`
Sto struct{} `json:"sto,omitempty"`

Nur NullMarshal `json:"nur"`
Nuo NullMarshal `json:"nuo,omitempty"`
}

var optionalsExpected = `{
Expand All @@ -53,7 +62,8 @@ var optionalsExpected = `{
"br": false,
"ur": 0,
"str": {},
"sto": {}
"sto": {},
"nur": null
}`

func TestOmitEmpty(t *testing.T) {
Expand Down Expand Up @@ -1082,9 +1092,9 @@ func TestMarshalRawMessageValue(t *testing.T) {
{map[string]any{"M": &rawNil}, `{"M":null}`, true},
{&map[string]any{"M": &rawNil}, `{"M":null}`, true},
{T1{rawNil}, "{}", true},
{T2{&rawNil}, `{"M":null}`, true},
{T2{&rawNil}, "{}", true},
{&T1{rawNil}, "{}", true},
{&T2{&rawNil}, `{"M":null}`, true},
{&T2{&rawNil}, "{}", true},

// Test with empty, but non-nil, RawMessage.
{rawEmpty, "", false},
Expand Down