encoding/json: unmarshal option to treat omitted fields as null #33854
Labels
FeatureRequest
Issues asking for a new feature that does not need a proposal.
NeedsInvestigation
Someone must examine and confirm this is a valid issue and not a duplicate of an existing one.
Milestone
Json objects have two types of null-like fields, either a null value for
foo
such as{"foo":null}
, or an omittedfoo
field such as{}
. When unmarshalling into a Golang struct, the field can't really be absent, but I can choose whether the field's type is nullable or not(*1). I don't want to preserve the distinction between json absent and null (one null-type is plenty), so I'd like the option to treat the absent field as if it werenull
, and map both null-like json types into the same Golang behaviour.(*1) See #33835 for proper
null
unmarshalling support, wherenull
into a non-nullable type returns an error, and user-defined types determine whether they can unmarshalnull
or not. This issue makes most sense in combination with that. The current behaviour is to treat both absent andnull
like absent when unmarshalling, and in combination with #33835, the (opt-in) behaviour I'm proposing is to treat both absent andnull
likenull
instead.The behaviour that I want to avoid is having the Golang field skipped over during unmarshalling when the json field is absent. If my Golang field is optional / some nullable type, it doesn't make a huge difference - the field will be skipped, stay at its zero value, which I can define as the same value I'd get unmarshalling
null
into it. The issue is when I have a non-nullable field - I've gone to the effort of saying my input has a defined structure with a defined non-nullable type, I want the unmarshaller to return an error if the input did not contain the structure I said it should. My proposal would return an error in this case, by treating the absent asnull
, then unmarshallingnull
into the non-nullable golang type, and in combination with (*1) that would return an error.The implementation I prefer is an opt-in
json.Decoder
flag along the lines ofOmittedAsNull()
, so I can set it once for my whole project. I'm less interested in anomittedasnull
struct tag, because I'd end up writing it on every struct field I define.Either way the code would be the same when they're used: after parsing an object into a struct, determine which struct fields were not visited, and unmarshal
null
into them.The text was updated successfully, but these errors were encountered: