golang/go

encoding/json: marshal does not obey omitempty for empty structures

crawford opened this issue · 11 comments

Continuing from #9585...

A struct value cannot be 'empty'

Why can't a struct value be empty? My understanding is that the purpose of "omitempty" is to avoid marshalling information that is implicitly understood (e.g. if a value is not set, then it should be the zero value). Given this understanding (which may be flawed; please correct me if I am wrong), it would make sense to compare each field value with the output of reflect.Zero (since this is the value that Go will create) and use this comparison as the basis for isEmptyValue.

Given the following type declaration:

type MyType struct {
    Field struct {
        SubField int `json:"subfield,omitempty"`
    } `json:"field,omitempty"`
}

I would expect MyType{} to json.Marshal into {} because there is no extra data needed to reconstruct this object. Instead, it marshals to {"field":{}}, even though this doesn't actually encode any more information. (http://play.golang.org/p/xZP2gafHY9)

I would expect that either:

This bites me with time.Time{} values often. Camlistore has its own time.Time alias, just so we can do JSON differently.

See also #4357, which may be a dup.

This bites me often too, I'm highly motivated to fix this for 1.6 if no one else takes it on first.

CL https://golang.org/cl/13914 mentions this issue.

rsc commented

FWIW, struct{} is an empty struct. A zero struct is not the same thing.

What is the difference?

Is var foo struct{} not the same as foo := struct{}{}?

Oh nevermind, I understand what you are getting at. Yes, when I said "empty struct", I actually intended "zero struct".

rsc commented

Not for 1.7, and I think we should leave omitempty completely alone. I've been thinking about going along with "omitzero" but there are other things to think about there.

@rsc yeah, I've been thinking about this as well (for whatever reason I seem to write a lot of Go-JSON interfaces) and I'm not sure that Go can adequately represent the JSON data. I'm of the opinion that Go would need algebraic types. Using another tag like "omitzero" would allow the programmer to direct the marshaller to do an appropriate conversion though. So I guess I'm also in favor of not changing "omitempty". Feel free to close.

dionb commented

I am having the same issue with encoding/xml. I like the omitzero idea.

adg commented

This is more or less the same issue as #11939. Let's focus discussion there.