Skip to content

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

Closed
@crawford

Description

@crawford

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:

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions