Development
en-US

Splitting encoding/json Into Two Layers and Putting It Back Together: Layering and Compatibility in Go's json/v2

Go 1.27 runs the old encoding/json package on top of v2: syntax (jsontext) and semantics (v2) are split apart, every behavioral difference is an option, and old and new code coexist in the same dependency graph without a flag day.

·19 min read·Lios09
#go#json#encoding#compatibility#security#api-design

1. The Real Protagonist This Time Is v1

In the Go team's anniversary post Go Turns 17 published on 2026-11-10, there is a section dedicated to JSON. It notes that encoding/json/v2 and encoding/json/jsontext were six years in the making before reaching GA in Go 1.27, and points out that several default behaviors of the old package—such as "silently accepting invalid UTF-8 or duplicate object keys and matching struct fields case-insensitively"—have turned into interoperability and security hazards today.

What stood out to me most wasn't the list of new features in v2, but the sentence right after:

the original encoding/json package is now implemented entirely in terms of v2 under the hood.

Anyone can write a new package. The hard part is taking a package depended on by millions of programs and bound by the Go 1 compatibility promise, replacing its entire implementation without breaking anyone, and still letting new code opt into stricter defaults. The answer json/v2 landed on is simple to state: split "JSON syntax" and "the meaning between JSON and Go values" into two layers, then turn every behavioral difference between v1 and v2 into an individually toggleable option. v1 is just v2 with a full preset of "legacy behavior" options applied.

I pieced together the timeline from the primary sources: in late 2020, Daniel Martí drafted the initial vision for v2; Joe Tsai joined while working on Go's protobuf API, because protojson couldn't use encoding/json (it neither supported the stricter JSON required by the protobuf spec nor enabled efficient streaming serialization); in October 2023 they opened GitHub discussion #63397; in January 2025 they filed the formal proposal #71497; Go 1.25 shipped it experimentally behind GOEXPERIMENT=jsonv2; and Go 1.27 promoted it to GA, accompanied by the introductory post A new Go API for JSON on 2026-11-04. The official blog specifically notes that this effort was driven primarily by contributors outside Google.

2. Permissive Defaults Break When Two Parsers Disagree

The JSON specification leaves plenty of room for ambiguity. RFC 8259 mandates UTF-8, yet doesn't say what to do when an object contains duplicate member names; name comparison is case-sensitive by convention, but only "typically." In those gaps, v1 picked the most permissive behavior. Looking at a single program in isolation, that feels convenient: even slightly dirty input still parses.

The trouble is that JSON is rarely read by only one program. The Security Considerations section of the encoding/json/v2 package documentation gives an example that nails the problem: one service handles authentication and authorization, another executes the request, and the second assumes the first already authorized it. If an attacker can craft a JSON payload that causes the two sides to disagree on "whose request this is," they can use user A's valid credentials to act as user B. The bug isn't that either parser is wrong—it's that two "valid" parsers arrived at different interpretations.

This isn't theoretical. The jsonv2 announcement post calls out CVE-2017-12635: Apache CouchDB's Erlang JSON parser and JavaScript JSON parser handled duplicate keys differently. When a _users document contained two roles keys, write authorization checked the second one, while subsequent role assignment for the new user read the first. An ordinary user could grant themselves _admin privileges that way.

I wrote a small program on Go 1.27.3 to put v1 and v2 defaults side by side. The third variant uses "v1 overall, except duplicate keys are rejected," which will come up again when we look at options:

package main

import (
	jsonv1 "encoding/json"
	"encoding/json/jsontext"
	"encoding/json/v2"
	"fmt"
	"strings"
)

type Req struct {
	User  string `json:"user"`
	Admin bool   `json:"admin"`
}

func run(label string, in string, unmarshal func([]byte, any) error) {
	var r Req
	if err := unmarshal([]byte(in), &r); err != nil {
		fmt.Printf("%s  err: %v\n", label, err)
		return
	}
	fmt.Printf("%s  ok:  %+v\n", label, r)
}

func main() {
	v1 := jsonv1.Unmarshal
	v2 := func(b []byte, v any) error { return json.Unmarshal(b, v) }
	mixed := func(b []byte, v any) error { // v1 semantics, except reject duplicate keys like v2
		return json.Unmarshal(b, v, jsonv1.DefaultOptionsV1(), jsontext.AllowDuplicateNames(false))
	}

	dup := `{"user":"alice","user":"root"}`
	run("dup   v1   ", dup, v1)
	run("dup   v2   ", dup, v2)
	run("dup   mixed", dup, mixed)

	caseIn := `{"user":"alice","ADMIN":true}`
	run("case  v1   ", caseIn, v1)
	run("case  v2   ", caseIn, v2)

	bad := "{\"user\":\"al\xffice\"}"
	run("utf8  v1   ", bad, v1)
	run("utf8  v2   ", bad, v2)

	junk := `{"user":"alice"} garbage`
	var r Req
	fmt.Println("junk  v1 Decoder.Decode:", jsonv1.NewDecoder(strings.NewReader(junk)).Decode(&r))
	fmt.Println("junk  v2 UnmarshalRead: ", json.UnmarshalRead(strings.NewReader(junk), &r))
}

Actual output:

dup   v1     ok:  {User:root Admin:false}
dup   v2     err: jsontext: duplicate object member name "user"
dup   mixed  err: duplicate object member name
case  v1     ok:  {User:alice Admin:true}
case  v2     ok:  {User:alice Admin:false}
utf8  v1     ok:  {User:al�ice Admin:false}
utf8  v2     err: jsontext: invalid UTF-8 within "/user" after offset 11
junk  v1 Decoder.Decode: <nil>
junk  v2 UnmarshalRead:  jsontext: invalid character 'g' after top-level value after offset 17

Let's walk through the parts that matter to me, line by line.

Duplicate keys. v1 silently keeps the last one, so user becomes root. If an upstream gateway uses a "first-wins" parser, it sees alice. v2 returns an error immediately and shuts the door on that ambiguity.

Case sensitivity. ADMIN matches the struct field tagged admin in v1, whereas v2 ignores it. This one is easy to underestimate: case-insensitive matching is itself another way to manufacture "duplicate keys." {"admin":false,"ADMIN":true} looks like two distinct keys to parsers in most languages, but to v1 it's the same field written twice. The package docs state plainly that this causes Go to interpret the same object differently from most other implementations. The introductory blog post adds that this matching was also a performance limitation in v1.

Invalid UTF-8. v1 silently replaces \xff with U+FFFD (the � in the output) without returning an error. The package docs bluntly call this replacement "a form of data corruption": the exact meaning of the string has been altered. If signature verification and storage each parse the payload separately, the two sides no longer see the same bytes.

Trailing garbage. This is a pitfall of API shape rather than defaults. Many developers reach for json.NewDecoder(r).Decode(v), but Decoder was designed for a stream of concatenated JSON values; once it finishes reading the first value, it stops and ignores the trailing garbage. In v2, UnmarshalRead means "this Reader contains exactly one value," so anything left over is an error.

There is one more change I didn't put in the program: nil slices and nil maps. v1 encodes them as null, while v2 encodes them as [] and {}. The rationale in the introductory post is that JSON implementations in many other languages refuse to decode null into a type expecting an array or object, and surveys showed most Go users prefer empty arrays anyway. The migration guide shows a Pet{Name: "Remi"} example where Nicknames changes from null to []. This one is different in nature from the items above—it's an interoperability trade-off rather than a security issue—and during migration it's the one most likely to bite you.

v2 doesn't tighten everything, either. Unknown fields are still ignored by default in both versions—you have to pass RejectUnknownMembers explicitly to reject them—and large integers unmarshaled into any still become float64 and lose precision in both. The package docs say as much: v2 "generally chooses more secure defaults than v1, but care should still be taken with large integers or unknown members." I appreciate that candor. Strict defaults are about eliminating semantic ambiguity, not doing input validation for you.

3. Why Split Syntax and Semantics Into Two Packages

The v2 introductory post divides JSON serialization into two concerns:

  • Syntax: processing text according to the JSON grammar, using the terms encode and decode;
  • Semantics: mapping between JSON values and Go values, using the terms marshal and unmarshal.

Once separated, jsontext handles only syntax and never touches reflection; encoding/json/v2 sits on top of it and decides things like "which struct field does this object member map to?"

The three layers of Go 1.27 JSON: encoding/json Marshal/Unmarshal simply calls v2 with DefaultOptionsV1; the v2 semantic layer uses reflection for struct tags, type methods, and caller-provided marshalers; the jsontext syntactic layer avoids reflection, streams Tokens and Values, and checks UTF-8 and duplicate keys; Options is a single shared type that passes across all layers

At first I thought this was just tidy code organization. After reading the list of v1's problems, it became clear that this split solves several long-standing issues at once.

v1's Marshaler interfaces drew the boundary in the wrong place. MarshalJSON() ([]byte, error) has to return a freshly allocated byte slice, which encoding/json then has to re-validate as legal JSON and reformat for indentation. UnmarshalJSON([]byte) is worse: before calling it, the library must scan the entire value just to find where it ends, and then the method parses those bytes all over again from the start. If the method recursively calls json.Unmarshal, the cost turns quadratic. The introductory post cites Kubernetes as an example: a service recursively parsed OpenAPI specs inside UnmarshalJSON, tanking performance (kube-openapi#315), and switching to UnmarshalJSONFrom reportedly "improved performance by orders of magnitude." I haven't verified that figure myself—just passing it along.

v2's new MarshalJSONTo(*jsontext.Encoder) and UnmarshalJSONFrom(*jsontext.Decoder) move that boundary: types write tokens directly to the Encoder or read tokens directly from the Decoder. Finding value boundaries and validating output become the job of the Encoder/Decoder state machine. Doing that requires a standalone syntax layer you can expose on its own, and that's what jsontext is.

v1's "streaming" wasn't really streaming. Even though v1's Encoder and Decoder accept an io.Writer and io.Reader, they buffer the entire JSON value in memory; Decoder.Token allocates heavily, and there is no corresponding token-writing API at all. jsontext's Decoder tracks nesting with a state machine and steps forward one token at a time:

package main

import (
	"encoding/json/jsontext"
	"fmt"
	"strings"
)

func main() {
	in := `{"items":[1,"two"],"ok":true}`
	dec := jsontext.NewDecoder(strings.NewReader(in))
	for {
		tok, err := dec.ReadToken()
		if err != nil {
			fmt.Println("stop:", err)
			return
		}
		fmt.Printf("%-6v %-5s at %q\n", tok.Kind(), tok.String(), dec.StackPointer())
	}
}

Actual output:

{      {     at ""
string items at "/items"
[      [     at "/items"
number 1     at "/items/0"
string two   at "/items/1"
]      ]     at "/items"
string ok    at "/ok"
true   true  at "/ok"
}      }     at ""
stop: EOF

Notice that colons and commas are not tokens. The jsontext docs explain that their positions are implied by the grammar, so they aren't given separate token representations. StackPointer() returns an RFC 6901 JSON Pointer, which is where within "/user" in the earlier error message came from. I really like that detail: errors can tell you which field failed, not just a byte offset.

Where strictness lives matters too. Duplicate-key and invalid-UTF-8 checks live in jsontext, controlled by jsontext options (AllowDuplicateNames, AllowInvalidUTF8); case-insensitive matching and how nil slices format are matters of "meaning," so their switches live in v2 (MatchCaseInsensitiveNames, FormatNilSliceAsNull). The payoff is that even if you skip reflection entirely and build a JSON-forwarding proxy straight on jsontext, you still get the exact same syntax checks as json.Unmarshal. Having a single implementation of syntax validation directly reduces the "two parsers disagree" problem from the previous section.

Options share a single type. The Options type exported by v1, v2, and jsontext is actually the exact same underlying type (go doc shows all three as aliases for jsonopts.Options), so options from all three layers can be mixed in a single call, with later options overriding earlier ones. Encoder and Decoder also expose an Options() method, so a custom MarshalJSONTo can inspect the caller's options. That fixes an old v1 wart: Decoder.DisallowUnknownFields stopped working as soon as execution entered a custom UnmarshalJSON, because there was no way to propagate options down the call stack. v2 fixes this at the interface level.

4. v1 = v2 + DefaultOptionsV1

Once every behavioral difference is modeled as an option, v1's implementation becomes almost boringly simple. Looking at the source bundled with Go 1.27.3, encoding/json's Unmarshal is literally one line:

func Unmarshal(data []byte, v any) error {
	return jsonv2.Unmarshal(data, v, DefaultOptionsV1())
}

The encoding/json package documentation lists every difference between v1 and v2 one by one, and each maps to an option: case-insensitive matching maps to MatchCaseInsensitiveNames and MatchCaseSensitiveDelimiter; the legacy definition of omitempty maps to OmitEmptyWithLegacySemantics; invoking pointer-receiver MarshalJSON methods only when the value is addressable maps to CallMethodsWithLegacySemantics; deterministic map key ordering maps to Deterministic; HTML character escaping maps to jsontext.EscapeForHTML; encoding time.Duration as integer nanoseconds maps to FormatDurationAsNano; and suppressing errors for malformed types (such as broken struct tags) maps to ReportErrorsWithLegacySemantics. DefaultOptionsV1() simply flips every one of those switches back to its legacy position.

Look back at the dup mixed line in the first program's output: it returned an error, but without the jsontext: prefix that pure v2 produced. I printed the concrete error type separately and confirmed it's v1's *json.SyntaxError; the source contains a transformSyntacticError helper that rewrites jsontext syntax errors into v1's error types and wording. So DefaultOptionsV1 preserves not just parsing results, but even the error types callers might assert against. That said, the experimental-phase blog post warned that under the reimplementation, details like "the exact wording of error messages" may still have observable differences.

What I find cleverest about this design is how it turns compatibility from a binary, package-level choice into a continuum you can configure per call site via options. The package docs lay out several stops along the spectrum from pure v1 to pure v2:

jsonv1.Marshal(v)                                    // pure v1
jsonv2.Marshal(v, jsonv1.DefaultOptionsV1())          // semantically equivalent to pure v1
jsonv2.Marshal(v, jsonv1.DefaultOptionsV1(),
	jsontext.AllowDuplicateNames(false))              // mostly v1, picking up one v2 behavior
jsonv2.Marshal(v, jsonv1.CallMethodsWithLegacySemantics(true)) // mostly v2, keeping one v1 behavior
jsonv2.Marshal(v)                                     // pure v2

One small detail from reading the source: inside the encoding/json directory, the legacy implementation (decode.go, etc.) and the new one (v2_decode.go, etc.) still coexist, gated by the goexperiment.jsonv2 build tag. In Go 1.27.3's internal/buildcfg, that experiment is enabled by default, and go list confirms encoding/json actually compiles the v2_*.go files. The old code is still sitting in the tree for now. I didn't find any documentation saying whether that build tag is a supported rollback switch, so I won't draw any conclusions about it.

5. No Flag Day: Mixing Both Versions in the Same Dependency Graph

Letting a single program migrate gradually isn't enough on its own. The real difficulty is the dependency graph: your service uses v2, a library you depend on is still on v1, and another library that library depends on has already implemented v2 methods. If v1 and v2 were two mutually oblivious implementations, the entire ecosystem would have to coordinate a single cutover date—a flag day.

The GA introductory post specifically addresses both directions:

  • You marshal a struct with v2, and one of its field types comes from a third-party package that only implements v1's MarshalJSON. No problem—v2 supports MarshalJSON out of the box.
  • Conversely, you're still calling v1, while that field's type has already implemented v2's MarshalJSONTo. Still no problem—because v1 runs on v2 underneath, it invokes MarshalJSONTo.

There is a nice side effect: backward-compatible v2 additions, like MarshalJSONTo methods or new struct tags such as embed, work for v1 callers without changing a line of calling code. The experimental-phase blog post calls this "feature inheritance," alongside two other benefits: gradual migration and reduced maintenance—fix a bug once and both versions benefit, with no backporting required.

Four-step migration: stay on encoding/json; switch to the v2 API while passing DefaultOptionsV1; append v2 behaviors one by one; finally keep only the few v1 options you truly depend on. Production services can use jsonsplit to run both implementations in parallel and report diffs. Bottom illustrates cross-version interoperability across dependencies

The Migration Guide opens with "you don't have to!"—v1 isn't going anywhere. For teams that do want to move, it lays out three paths depending on risk tolerance:

  1. All-at-once: swap the import, run tests, ship. Good for simple programs or places where breakage is cheap.
  2. Option-by-option: convert calls to json.Marshal(v, jsonv1.DefaultOptionsV1()) first. The guide calls this step "trivial and safe," since that's literally how v1 is implemented. Then layer v2 behaviors on one by one afterward. When something breaks, those options also double as a way to bisect which specific behavioral change caused it.
  3. jsonsplit: aimed at production services. github.com/go-json-experiment/jsonsplit wraps Marshal and Unmarshal and lets you configure CallBothButReturnV1: it runs both implementations, returns the v1 result, and reports any discrepancies. Turning on AutoDetectOptions can even pinpoint which option explains a diff. The guide is upfront about the cost: running both roughly doubles marshaling overhead, and auto-detection adds more runs on top, so SetMarshalCallRatio lets you sample only a fraction of calls.

One line in the guide feels especially grounded: the API migration itself is trivial—changing the import makes json.Marshal(v) compile right away; the hard part is behavioral changes. The compiler won't warn you when Nicknames turns from null into [], your test suite might not catch it, and a downstream consumer can still blow up on it.

6. How I'd Weigh the Trade-Offs

This design isn't free, and there are a few costs I'd watch closely.

The option space is large, making "what behavior is actually active here?" harder to tell at a glance. Previously, encoding/json had one behavior. Now the exact same json.Marshal call can behave differently depending on the options passed in and whether a struct tag specifies case:ignore or case:strict (field-level options override caller options). I would centralize a project's chosen option set in a single package-level variable shared by all call sites, instead of letting each call site assemble its own mix.

Some "more correct" behaviors are breaking changes for existing systems. Nil slices becoming [], maps no longer encoding in deterministic key order (v2 requires Deterministic for that), time.Duration failing with no default representation, and omitempty switching to JSON-level emptiness—these are all better defaults for greenfield code. But if a cache key is derived from serialized bytes, or snapshot tests compare raw JSON output, non-deterministic map ordering alone will make them flaky. I'd put those items right at the top of any migration checklist.

Strict defaults only deliver full protection when both sides are strict. In the split auth/execution scenario from Section 2, if the gateway is written in another language and allows duplicate keys, Go rejecting them only fails the request rather than making both sides agree. Still, that's the right direction: failing closed is far better than silently acting on divergent interpretations.

On performance, I'll stick to quoting the official claims. The introductory post describes v2 Marshal as "roughly at parity with v1"—sometimes a bit faster, sometimes a bit slower—and Unmarshal as "significantly faster," "with benchmarks demonstrating improvements of up to 10x." The anniversary post adds that v1 callers get faster unmarshaling simply by upgrading Go. I haven't run benchmarks myself, so I'm relaying those figures as stated rather than endorsing them. What matters more to me is the structural point: as long as a custom type sticks with UnmarshalJSON([]byte), you can't avoid double parsing—getting the real win requires migrating to UnmarshalJSONFrom.

(The same anniversary post also introduces the goroutineleak profiler, which reuses the GC's reachability analysis to find goroutines that can never wake up. Unrelated to JSON, so I'll leave it there.)

7. My Takeaways

  1. Layering isn't cosmetic—it gives strictness a single home. Syntactic checks like duplicate keys and UTF-8 validation happen once in jsontext; the reflection layer, the v1 compatibility layer, and hand-written streaming code all go through the same state machine. To me, that's the most transferable lesson here: if you want fewer cases of "two parsers disagree," start by having only one parser inside your own codebase.

  2. Turning every behavioral difference into an option is the core compatibility technique. It replaces a binary jump between v1 and v2 with a continuum you can slide across per call site, with v1 sitting at one end. The next time I design a library that needs a major-version upgrade, my first question will be whether every difference between old and new behavior can be expressed as a toggle. If so, the old version becomes a preset configuration of the new one instead of a second implementation to maintain.

  3. Interoperability matters more than migration tooling. jsonsplit is handy, but what actually eliminates the flag day is the two-way contract: v2 honors v1 methods, and v1 dispatches to v2 methods underneath. As long as there aren't two mutually incompatible implementations in the dependency graph, every package can upgrade on its own schedule.

  4. How I'd adopt it: For new code, use v2 directly with its defaults, adding RejectUnknownMembers explicitly where needed. For existing services, switch call sites to DefaultOptionsV1() first, then enable v2 behaviors from lowest risk to highest: duplicate keys and invalid UTF-8 first, since those represent bad data anyway; nil slices and map ordering last, since they're the most likely to affect downstream consumers. For services exposing external JSON APIs, I'd run sampled diffs with jsonsplit in production before cutting over.

  5. What impresses me most is the restraint. Six years from experimental package to GOEXPERIMENT to GA, v1 was never deprecated, and the first line of the migration guide's "Why migrate?" pitch is literally "you don't have to!" For a Go package that the experimental blog post notes is the fifth most imported in the ecosystem, not pressuring users to move is itself part of the compatibility promise.

References

Related Posts

Repurposing GC Reachability to Catch Partial Deadlocks: Inside Go 1.27's goroutineleak Profiler

Go 1.27 ships the goroutineleak profiler in runtime/pprof and net/http/pprof. Rather than sampling stacks or guessing from goroutine counts, it adapts Go's tri-color mark-and-sweep GC to compute an inductive liveness fixpoint LIVE+(g)—pinpointing permanently blocked goroutines in production with near-zero false positives, while carrying sharp boundaries around memory overreach, O(n²) daisy-chains, and non-channel blocking.

KV-Cache-Aware Inference Routing: Reading Kinference and Benchmarking in Go

A walkthrough of Kinference's PredictedTTFT and InferencePolicy, paired with a Go mock benchmark comparing round-robin, prefix-affinity, and combined scoring under hot-prefix workloads.

GitHub Rubicon: Coordinating Only Ref Updates—Benchmarking Repo-Wide Locks vs. Per-Ref CAS in Go

GitHub's new Git storage architecture, Rubicon, stores immutable objects in Azure Blob Storage, delegates reference and pack manifest transactions to Ref-CAS, and uses disposable virtual replicas and dedicated compaction nodes for reads, writes, and maintenance. Based on the full official post, this article explains the publication boundary and the workload assumptions behind per-ref parallelism, accompanied by a runnable minimal Go implementation: SHA-256 immutable objects, file and directory fsync before CAS, an ordered in-memory per-ref log, and a repo-wide mutex baseline. Across 36 runs, all 216,000 acknowledged pushes passed in-process verification. At N=32, median throughput on distinct refs was 15,216 push/s vs. 4,397 for the repo-wide lock; on the same ref, it dropped to 858 vs. 3,937 with a 93.6% attempt conflict rate. The ref log is not durable, so this proves neither crash recovery nor distributed consensus, and the numbers cannot be compared against GitHub's internal 7,200 push/s figure.