Skip to content
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

encoding/json: rendered empty struct on omitempty #59170

Closed
IGLOU-EU opened this issue Mar 21, 2023 · 2 comments
Closed

encoding/json: rendered empty struct on omitempty #59170

IGLOU-EU opened this issue Mar 21, 2023 · 2 comments

Comments

@IGLOU-EU
Copy link

IGLOU-EU commented Mar 21, 2023

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":{}}
@zephyrtronium
Copy link
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
Copy link
Author

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

@golang golang locked and limited conversation to collaborators Mar 20, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants