Skip to content

jsonpb: with EmitDefaults=true, nil map/slice should marshal to "null" #406

Closed
@cybrcodr

Description

@cybrcodr

Current implementation with EmitDefaults=true, marshals map to JSON {} and slice to JSON [] regardless of whether map/slice is nil or empty instance. Spec does not dictate any rules on this afaik. Note that if EmitDefaults=false, empty or nil is treated as "default" value and hence is omitted in the JSON data, which I think is appropriate.

With commit 748d386, library unmarshals JSON "null" to nil map/slice instead of empty instance for the same rationale as mentioned in PR #394. So perhaps it would be more intuitive/natural to make the distinction in the reverse direction to distinguish nil vs empty, i.e. empty map marshals to {}, nil map marshals to null, empty slice marshals to [], nil slice marshals to null.

The other part that comes with the above suggestion is what to do with WKT Struct and ListValue. Struct wraps a map field "fields" and ListValue wraps a repeated field "values". However, marshaling these types are typically based on marshaling the inner fields directly if not empty/nil. If one sets a field with empty &Struct{}, the inner map "fields" is still nil. Current implementation marshals it into {} regardless of EmitDefaults.

@zombiezen -- thoughts on this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions