Skip to content

proposal: encoding/json/v2: escape hatch to omit & override field #75827

@jacobzim-stl

Description

@jacobzim-stl

Proposal Details

When dealing with malfunctioning external systems, escape hatches in the JSON system can be valuable to unblock progress.

I propose the following types are added to encoding/json/v2

package json

type OmitField     struct{}
type OverrideField jsontext.Value

Let's say a misbehaving server rejects the presence of the field "valid", and wants a JSON number for "id". It would be valuable to explicitly omit, or override the field. User may be part of a larger structure, and it would be inconvenient to rewrite the type.

type User struct {
	Name      string         `json:"name'`
	Id        string         `json:"id"`
	Valid     bool           `json:"valid"`
	ExtraJSON map[string]any `json:",unknown"`
}
user := User{
	Name:      "John Doe",
	ExtraJSON: map[string]any{
		"valid": json.OmitField,
		"id":    json.OverrideField(`1234567890123456`),
	},
}
// Marshals to `{"name":"John Doe","id":1234567890123456}`

In the current implementation, trying to do this would result in an error, since duplicate fields can't be marshaled.

I'd suggest that this only apply for inline fallback map[~string]T fields, perhaps only with json:",unknown". The alternative of writing a custom MarshalFunc adds complexity, and doesn't provide per-instance flexibility.

Thanks @dsnet for your hard work and designs on json/v2

Metadata

Metadata

Assignees

No one assigned

    Labels

    LibraryProposalIssues describing a requested change to the Go standard library or x/ libraries, but not to a toolProposal

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions