Skip to content

encoding/json: Add "nonil" struct tag for json encoding of nil slices/maps #27813

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
20 changes: 19 additions & 1 deletion src/encoding/json/encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,11 @@ import (
// false, 0, a nil pointer, a nil interface value, and any empty array,
// slice, map, or string.
//
// The "nonil" option specifies that if the field is a slice or map
// of nil value, then the value encoded will be [] or {} respectively (instead
// of "null"). If both "nonil" and "omitempty" are present, then "nonil" is
// ignored. If the field is not a slice or map, "nonil" does nothing.
//
// As a special case, if the field tag is "-", the field is always omitted.
// Note that a field with name "-" can still be generated using the tag "-,".
//
Expand Down Expand Up @@ -656,7 +661,18 @@ FieldLoop:
e.WriteString(f.nameNonEsc)
}
opts.quoted = f.quoted
f.encoder(e, fv, opts)

if f.noNil {
if f.typ.Kind() == reflect.Slice && fv.IsNil() {
e.WriteString("[]")
} else if f.typ.Kind() == reflect.Map && fv.IsNil() {
e.WriteString("{}")
} else {
f.encoder(e, fv, opts)
}
} else {
f.encoder(e, fv, opts)
}
}
if next == '{' {
e.WriteString("{}")
Expand Down Expand Up @@ -1039,6 +1055,7 @@ type field struct {
index []int
typ reflect.Type
omitEmpty bool
noNil bool
quoted bool

encoder encoderFunc
Expand Down Expand Up @@ -1156,6 +1173,7 @@ func typeFields(t reflect.Type) []field {
index: index,
typ: ft,
omitEmpty: opts.Contains("omitempty"),
noNil: !opts.Contains("omitempty") && opts.Contains("nonil"),
quoted: quoted,
}
field.nameBytes = []byte(field.name)
Expand Down
10 changes: 9 additions & 1 deletion src/encoding/json/encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ type Optionals struct {

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

Slh []string `json:"slh,nonil"`
Slb []string `json:"slb,omitempty,nonil"`

Mh map[string]interface{} `json:"mh,nonil"`
Mb map[string]interface{} `json:"mb,omitempty,nonil"`
}

var optionalsExpected = `{
Expand All @@ -52,7 +58,9 @@ var optionalsExpected = `{
"br": false,
"ur": 0,
"str": {},
"sto": {}
"sto": {},
"slh": [],
"mh": {}
}`

func TestOmitEmpty(t *testing.T) {
Expand Down