Go encoding/json v2 Explained: How the Rewrite Works

Layers of Go encoding/json v2 from bytes to Go types

Go’s encoding/json v2 package is a ground-up rewrite of the standard library’s JSON code, and in Go 1.27.3 it’s enabled by default. The old encoding/json still exists, but it is now a thin wrapper over v2 that switches back to the legacy defaults.

A detailed walkthrough of the source shows how v2 is organized and why it’s quick.

Why a rewrite was needed

Moving to encoding/json v2 fixes defaults that were set in Go 1.0. Some v1 behavior couldn’t change without breaking existing programs. It accepts duplicate object names and invalid UTF-8, encodes nil slices as null, and matches field names without regard to case. The v2 package uses stricter defaults, so duplicate names are rejected unless you turn on the AllowDuplicateNames option.

Four stacked horizontal bands, top to bottom: “encoding/json (v1)” with the note “thin wrapper: v2 with v1 options”; “encoding/json/v2” with the note “semantic layer: Go values ⇄ tokens (reflection)”; “encoding/json/jsontext” with the note “syntactic layer: Encoder, Decoder, state machine”; and “internal/jsonwire” with the note “bytes: quote, unquote, parse numbers”. A straight arrow goes down from each band to the band below it, three arrows in all. To the right of bands 2 to 4 there is a narrow vertical box labelled “jsonopts + jsonflags: all options”.
Image: Internals for Interns

A stack of packages

The JSON code is no longer a single package. Each layer relies only on the ones beneath it:

  • internal/jsonwire works on raw bytes, measuring strings, numbers and literals such as true or null.
  • encoding/json/jsontext knows the JSON grammar. It groups bytes into tokens and checks that brackets close and names and values arrive in the right order. It knows nothing about Go types.
  • encoding/json/v2 connects JSON to Go types: objects into structs, arrays into slices.
  • jsonopts and jsonflags carry options through every layer.
  • encoding/json, the v1 package, calls the v2 Unmarshal with options that restore the old behavior.

So there is one engine with two sets of defaults.

Two rows of bit cells under the column headers “Deterministic”, “AllowDuplicateNames”, “Multiline” and, slightly apart, “value”. A bracket labelled “which option” spans the first three columns, and the label “true / false” points at the value column. Row 1 comes from the call json.Deterministic(true) and holds 1, 0, 0 and value 1, with the Deterministic cell and the value cell in red. Row 2 comes from the call jsontext.AllowDuplicateNames(false) and holds 0, 1, 0 and value 0, with the AllowDuplicateNames cell in red.
Image: Internals for Interns

Options packed into bits

Each yes/no option is one bit in a 64-bit number. Two numbers track them: Presence records which options were passed, and Values records whether each is on. Setting a flag combines the switch with Presence using OR, and multiplies the switch by the value bit to update Values. True and false therefore run the same instructions with no branch. Reading an option is a single bitwise AND, and one AND can test several options at once. The options are checked constantly in the busiest loops, so each check costs only a couple of CPU instructions.

Two panels, “Set” and “Get”. Every number is a strip of three bit cells for Deterministic, AllowDuplicateNames and Multiline. In the Set panel, step 1: Deterministic(true) is the strip 1 0 0 with a value cell of 1; an arrow labelled “OR” leads to Presence 1 0 0, and an arrow labelled “× value (1)” leads to Values 1 0 0. Step 2: AllowDuplicateNames(false) is the strip 0 1 0 with a value cell of 0; “OR” leads to Presence 1 1 0, and “× value (0)” leads to Values 1 0 0, marked “nothing added”. In the Get panel, two stacked calculations: Values 1 0 0 AND Deterministic 1 0 0 gives 1 0 0, “not 0 → on”; Values 1 0 0 AND AllowDuplicateNames 0 1 0 gives 0 0 0, “0 → off”. Every 1 in the Deterministic column is red, and so is “on”.
Image: Internals for Interns

How a document gets read

Parsing starts at the bottom. The first character of a JSON value reveals its type, so jsontext picks the right jsonwire helper. A quote starts a string, a digit or minus sign starts a number, and a t starts true. The helper returns only a length, without copying anything. For “name” it returns 6, the length with both quotes.

Jsontext then checks the grammar with a state machine, a stack with one 64-bit entry per open object or array. Each entry holds a bit for object or array, two bits for duplicate-name checks and a 61-bit counter of names and values seen. An even count means a name comes next, and an odd count means a value. That lets the decoder drop colons and commas, since the stack already knows where they go. It can also build a JSON Pointer such as /meta/level for error messages without building a tree.

Arshalers and duplicate checks

In the v2 layer, the pointer passed to Unmarshal supplies both a place to write and a type, found through reflection. For each type, v2 builds an arshaler, a marshal and unmarshal pair, once and caches it. A field table maps JSON names to struct fields and is built lazily, which stops a self-referencing type from causing an endless loop. The decoder itself comes from a sync.Pool so its internals aren’t reallocated on every call.

Duplicate names in structs are caught with one more bitmask. Each field has a numbered id, and a seen bit is set when its name appears. A second appearance finds the bit already set and returns an error. One uint64 covers 64 fields.

Marshalling and the fast path

Writing reverses the trip. The string arshaler knows a string is valid right after a name, so when no whitespace options are set, it appends the colon and the quoted value directly and bumps the state machine counter. Numbers and booleans take the same shortcut. Null goes through the slower WriteToken route.

What it means for Go developers

The speed of encoding/json v2 comes from many small decisions rather than one big trick: bit-packed options, one-time arshaler construction and skipping checks that can’t fail. Most programs keep working through the v1 wrapper, but anyone relying on lenient v1 defaults should test against the stricter ones. The author’s next article covers analyzers and go vet.

Source: Internals for Interns

Written by

Saksham Bhargava

Saksham Bhargava runs Alteroid and has been writing about consumer technology for over five years, covering iPhone, Android, Windows, AI tools and gaming. With an MCA and six years of hands-on web development experience, he tests the features he writes about on his own devices and focuses on clear, practical guides that solve real problems. Away from the screen, he enjoys travelling to places most tourists skip.