NewsCrawler.org

Go 1.27 ships stable encoding/json/v2 with a new jsontext package

The Go Blog announces that encoding/json/v2 and encoding/json/jsontext are stable and generally available in Go 1.27, after a year of feedback on the experimental API. The current encoding/json has behavioral flaws: it accepts invalid UTF-8 (RFC 8259 requires valid UTF-8), accepts duplicate object member names (exploited before, as in CVE-2017-12635), marshals nil slices and maps as JSON null even though most surveyed Go users prefer empty arrays or objects, resolves field names case-insensitively, and inconsistently calls pointer-receiver MarshalJSON methods — a bug that cannot be fixed because too many applications depend on it.

API deficiencies include json.NewDecoder(r).Decode(v) failing to reject trailing junk, options that do not work with Marshal/Unmarshal functions (DisallowUnknownFields loses its effect with a custom UnmarshalJSON), and Compact, Indent, and HTMLEscape writing to bytes.Buffer instead of []byte or io.Writer. Performance limitations come from the public API itself: MarshalJSON forces allocation and reformatting, UnmarshalJSON forces the package to parse a value fully before and the method to parse it again, Encoder and Decoder buffer entire values, and recursive Marshal/Unmarshal calls become quadratic.

Fixing encoding/json directly is impossible under the Go 1 compatibility promise, so the changes ship in a separate v2 namespace. The jsontext package provides syntactic functionality (encode/decode, Encoder/Decoder with WriteValue, ReadToken and similar methods), while json/v2 provides semantic functionality (marshal/unmarshal) that assigns meaning to JSON in relation to Go values.

Read the original go.devDiscussion

Sources

Terms

  1. marshaling — Converting Go values into a serialized format like JSON (unmarshaling is the reverse).
  2. RFC 8259 — The current Internet standard defining the JSON data format.
  3. pointer receiver — A method declared on a pointer to a type, affecting how the method may be invoked.
  4. Go 1 compatibility promise — The Go project's guarantee that Go 1 programs keep compiling and behaving the same in newer releases.

Published: First seen: Читать по-русски

Open as a page