Liza Shulyayeva

Tiny changes to upgrade to Go's new `encoding/json/v2` pkg

Just a quick one!

Go has a new API for JSON and I’ve gone through and upgraded Eir’s endpoints to use it.

Here are some of the changes for a few different usages of encoding/json v1:

Swapping the import

 import (
        "bytes"
        "context"
-       "encoding/json"
+       "encoding/json/jsontext"
+       "encoding/json/v2"
        "log"

Writing directly to an io.Writer

 func JSONResponse(w http.ResponseWriter, status int, data interface{}) {
        w.Header().Set("Content-Type", "application/json")
        w.WriteHeader(status)
-       json.NewEncoder(w).Encode(data)
+       json.MarshalWrite(w, data)
 }

Encoding through a jsontext.Encoder

        w.Header().Set("Content-Type", "application/json")
        w.WriteHeader(http.StatusOK)
-       _ = json.NewEncoder(w).Encode(users)
+       _ = json.MarshalEncode(jsontext.NewEncoder(w), users)

Decoding from a stream

        var req LoginRequest
-       if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+       if err := json.UnmarshalDecode(jsontext.NewDecoder(r.Body), &req); err != nil {
                utils.BadRequest(w, utils.MsgInvalidRequestBody)
                return
        }

Reading directly from an io.Reader and rejecting unknown fields

-       dec := json.NewDecoder(r.Body)
-       dec.DisallowUnknownFields()
-       if err := dec.Decode(&reqBody); err != nil && !errors.Is(err, io.EOF) {
+       if err := json.UnmarshalRead(r.Body, &reqBody, json.RejectUnknownMembers(true)); err != nil {
                utils.ErrorResponseWithContext(r, w, http.StatusBadRequest, "Invalid JSON in request body", err, userID, map[string]interface{}{
                        "endpoint": "/v1/meditations",
                })

Indented output

-       enc := json.NewEncoder(os.Stdout)
-       enc.SetIndent("", "  ")
-       if err := enc.Encode(parts); err != nil {
+       if err := json.MarshalWrite(os.Stdout, parts, jsontext.WithIndent("  ")); err != nil {

json.RawMessage -> jsontext.Value

        // Validate it's valid JSON (schema is enforced by API)
-       var check json.RawMessage
+       var check jsontext.Value
        if err := json.Unmarshal([]byte(text), &check); err != nil {

Potentially less tiny impact

Even if the code changes themselves are small, some updates with v2 may be worth keeping in mind:

dev
© 2026 · Liza Shulyayeva · Top · RSS · privacy policy