Skip to content

encoding/json: rendered empty struct on omitempty #59170

Closed
@IGLOU-EU

Description

@IGLOU-EU

What version of Go are you using (go version)?

$ go version
go version go1.20 linux/amd64

What did you do?

Marshal a struct into Json with omitempty.
https://go.dev/play/p/nTyS0p_JP3E

type A struct {
	AA string `json:"aa,omitempty"`
	AB []struct {
		ABA int    `json:"aba,omitempty"`
		ABB string `json:"abb,omitempty"`
	} `json:"ab,omitempty"`
	AC struct {
		ACA int `json:"aca,omitempty"`
	} `json:"ac,omitempty"`
}

func main() {
	a, b := json.Marshal(A{AA: "Hum"})
	fmt.Printf("%s\n%v", a, b)
}

What did you expect to see?

{"aa":"Hum"}

What did you see instead?

{"aa":"Hum","ac":{}}

Activity

zephyrtronium

zephyrtronium commented on Mar 21, 2023

@zephyrtronium
Contributor

See also #11939 and #45669, and tangentially #22480. This is working as currently documented:

The "omitempty" option specifies that the field should be omitted from the encoding if the field has an empty value, defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string.

With respect to omitempty, there is no "empty" value of any struct type.

IGLOU-EU

IGLOU-EU commented on Mar 21, 2023

@IGLOU-EU
Author

Thank you, that true. I go read their's proposal !

locked and limited conversation to collaborators on Mar 20, 2024
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

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @zephyrtronium@gopherbot@IGLOU-EU

        Issue actions

          encoding/json: rendered empty struct on omitempty · Issue #59170 · golang/go