Skip to content

proposal: encoding/json: add a generic Decode function #59053

@joerdav

Description

@joerdav

I believe with generics now in place a new more convenient Decode function could be added to the encoding/json package, amongst other encoding/* packages.

Proposed:

func handler(w http.ResponseWriter, r *http.Request) {
	request, err := json.NewDecoder(r.Body).DecodeInto[MyStruct]()
	if err != nil {
		...
	}
	...
}

Existing:

func handler(w http.ResponseWriter, r *http.Request) {
	var request MyStruct
	err := json.NewDecoder(r.Body).Decode(&request)
	if err != nil {
		...
	}
	...
}

The benefit of this API is not only is it more concise, but it removes the possibility of a json: Unmarshal(nil) error.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    Status
    Incoming

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions