TL;DR
Go’s encoding/json/v2 is the first real rewrite of the standard library’s JSON handling since Go 1.0. The Go team reports unmarshaling up to 10x faster, with marshaling roughly at parity. It also cleans up a pile of long-standing footguns and moves configuration from magic struct tags into explicit function options. The catch: it changes several v1 defaults you may be quietly relying on. Nil slices now encode as [] instead of null, duplicate object keys are rejected, field matching is case-sensitive, and time.Duration has no default encoding at all. Since Go 1.27 (August 2026) it’s a stable package you import with no flag, and plain encoding/json now runs on the v2 engine while keeping v1 behavior. On Go 1.25 and 1.26 it still sits behind GOEXPERIMENT=jsonv2. This is a practical walkthrough of the changes that will bite you and how to migrate without breaking your API contracts.
Every snippet below was re-run on go1.27.3 (Go Playground) on October 29, 2026; the outputs shown are from that run.
Part of our Modern Go in 2026 series — the complete guide connects JSON v2 to iterators, generic methods, the Green Tea GC, and where Go beats Rust.
Why a second JSON package at all
encoding/json shipped with Go 1.0 in 2012 and barely changed since. That stability paid off for a long time, then slowly turned into a tax. The v1 package carried a set of decisions that looked reasonable in 2011 and aged into daily annoyances: it silently accepts duplicate object keys, replaces invalid UTF-8 with the Unicode replacement character instead of erroring, and marshals a nil slice as null rather than an empty array. Each of those has bitten real production code.
The most expensive of the three is the nil-slice-as-null behavior. Picture a Go service returning a list of items to a TypeScript frontend. When the list is empty, the backend sometimes sends "items": null and sometimes "items": [], depending on whether a slice was initialized or left nil somewhere upstream. The frontend calls .map() on the response and blows up only on the null path: an intermittent, hard-to-reproduce crash that comes down to a Go zero-value quirk. The v1 fix is a make([]Item, 0) and a mental note. v2 fixes it at the source.
That is the spirit of the whole package. The official experimental announcement from September 2025 notes that Go’s JSON support dates back almost 15 years, and presents v2 as fixing v1’s long-standing shortcomings while keeping the API recognizable. If you’ve written Go, json.Marshal and json.Unmarshal still work the way you expect. They just have saner defaults and a much faster engine underneath.
If you’re tracking where the language is heading more broadly, this fits the same evolutionary arc as the Go 1.26 and 1.27 standard-library changes: fewer surprises, more explicit control.
What’s actually in the box
json/v2 is not one package but two, split along a clean line:
encoding/json/jsontexthandles syntax: the raw grammar of JSON. It gives you a streamingEncoderandDecoder, plusValueandTokentypes, and it doesn’t touch reflection at all. Think of it as the tokenizer layer.encoding/json/v2handles semantics: mapping Go values to and from JSON. This is whereMarshal,Unmarshal, and the struct-tag machinery live.
That separation pays off in performance-sensitive code, because you can drop down to jsontext and stream tokens without paying for reflection when you don’t need it. For everyday use you’ll import v2 and never think about the split.
Turning it on
On Go 1.27 or newer there is nothing to turn on: encoding/json/v2 and encoding/json/jsontext are ordinary standard-library packages, with no go get and no flag. On Go 1.25 and 1.26 the same packages ship in your toolchain but stay hidden unless you build with the experiment flag:
# Go 1.25 / 1.26 only; Go 1.27+ needs no flag
GOEXPERIMENT=jsonv2 go run main.go
# Persist it for a session
export GOEXPERIMENT=jsonv2
go build ./...
go test ./...
Without the flag, Go 1.26 refuses the import outright. On the Playground’s go1.26.10 backend the build fails with imports encoding/json/v2: build constraints exclude all Go files. On go1.27.3 the same file compiles as-is:
// main.go: go run main.go (Go 1.27+), or GOEXPERIMENT=jsonv2 go run main.go (1.25/1.26)
package main
import (
"fmt"
json "encoding/json/v2"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Roles []string `json:"roles"`
}
func main() {
u := User{ID: 7, Name: "Ada"} // Roles left nil on purpose
b, err := json.Marshal(u)
if err != nil {
panic(err)
}
fmt.Println(string(b))
}
Running it on go1.27.3 prints:
{"id":7,"name":"Ada","roles":[]}
Swap the import back to plain encoding/json and the same struct marshals to {"id":7,"name":"Ada","roles":null}. That single difference is the one most likely to change bytes on the wire in your service, so it’s worth internalizing before anything else.
What Go 1.27 did to plain encoding/json
The part of the 1.27 release that touches every Go service is the v1 package. Per the Go 1.27 release notes, encoding/json “is now backed by the v2 implementation” and its marshaling and unmarshaling behavior “is preserved, but the exact text of error messages may differ.” Upgrading the toolchain gives your existing json.Unmarshal calls the faster engine without the new defaults. The same run confirms the old semantics survive on 1.27: v1 still keeps the last of two duplicate "id" keys, still fills a name field from "NAME", and still writes null for a nil slice.
// same User type, but importing plain "encoding/json"
u := User{ID: 7, Name: "Ada"}
b, _ := json.Marshal(u)
fmt.Println(string(b))
var d User
err := json.Unmarshal([]byte(`{"id":1,"id":2,"NAME":"Ada"}`), &d)
fmt.Printf("v1 dup+case: err=%v id=%d name=%q\n", err, d.ID, d.Name)
{"id":7,"name":"Ada","roles":null}
v1 dup+case: err=<nil> id=2 name="Ada"
If the swap does break something, building with GOEXPERIMENT=nojsonv2 restores the original v1 implementation. The notes say that opt-out “is expected to be removed in a future release” and ask you to file an issue if you need it, so treat it as a stopgap.
The standalone module github.com/go-json-experiment/json, where v2 was developed, now describes itself as a mirror of the stdlib package and declares go 1.26 in its go.mod. It’s no longer a route for running v2 on Go 1.23 or 1.24. If you’re on an old toolchain, upgrading is the path.
The breaking changes, ranked by how likely they are to bite
The encoding/json package docs list 16 behavioral differences between v1 and v2. These are the six most likely to bite, most disruptive first. Every one is controllable: v2 keeps the old behavior available as an option, it’s just no longer the default.
| Behavior | v1 default | v2 default | How to restore v1 |
|---|---|---|---|
| Nil slice | null | [] | json.FormatNilSliceAsNull(true) |
| Nil map | null | {} | json.FormatNilMapAsNull(true) |
| Field matching | case-insensitive | case-sensitive | json.MatchCaseInsensitiveNames(true) or case:ignore tag |
| Duplicate object keys | accepted | rejected | jsontext.AllowDuplicateNames(true) |
| Invalid UTF-8 | replaced silently | rejected | jsontext.AllowInvalidUTF8(true) |
time.Duration | encoded as int64 nanoseconds | no default; marshal and unmarshal both error | json.FormatDurationAsNano(true) (from encoding/json) |
Case sensitivity is the sneaky one
The nil-slice change is loud. You’ll see it in the first test that checks a response body. Case sensitivity is quiet, because it fails by silently not matching rather than by erroring. Consider input from an API that uses SCREAMING_CASE or PascalCase keys:
data := []byte(`{"NAME":"Ada"}`)
var u User // Name is tagged json:"name"
if err := json.Unmarshal(data, &u); err != nil {
panic(err)
}
fmt.Printf("Name=%q\n", u.Name)
Output:
Name=""
In v1 that would have populated u.Name with "Ada" because matching ignored case. In v2 the field stays at its zero value and no error is raised. If you consume upstream JSON whose casing doesn’t exactly match your tags, opt back in per-field:
type User struct {
Name string `json:"name,case:ignore"`
}
Or globally at the call site with json.MatchCaseInsensitiveNames(true). I’d reach for the per-field tag, since it documents which fields have loose upstream contracts instead of loosening the whole struct.
Duplicate keys now error
v1 happily unmarshaled {"id":1,"id":2} and kept the last value. That’s a genuine security hole: different parsers picking different values for the same key is the root of a whole class of request-smuggling and access-control bugs. v2 rejects it:
data := []byte(`{"id":1,"id":2}`)
var u User
err := json.Unmarshal(data, &u)
fmt.Println(err != nil) // true
fmt.Println(err)
On go1.27.3 that prints:
true
jsontext: duplicate object member name "id"
If you have a legitimate reason to accept duplicates, passing jsontext.AllowDuplicateNames(true) restores the old leniency; with it, the same input decodes cleanly and keeps the last value (id=2). That option and AllowInvalidUTF8 live in the jsontext package, since they’re syntactic, but you pass them straight to json.Unmarshal like any other option. Think hard before you reach for it.
time.Duration stops encoding at all
This is the change that turns a working config struct into a runtime error. v1 wrote a time.Duration as an integer count of nanoseconds. The v2 package refuses to pick a representation:
type Cfg struct {
Timeout time.Duration `json:"timeout"`
}
b, err := json.Marshal(Cfg{Timeout: 1500 * time.Millisecond})
fmt.Printf("v2: %s err=%v\n", b, err)
v2: {"timeout" err=json: cannot marshal from Go time.Duration within "/timeout": no default representation
Unmarshaling fails the same way, whether the input is 1500000000 or "1.5s". During the experiment the fix was a format:nano tag option. Go 1.27 removed the format tag option entirely, and on go1.27.3 the old tag now fails with Go struct field Timeout has unsupported `format` tag option. The supported switch is an option that lives in the v1 package, which you pass to the v2 call:
import (
v1 "encoding/json"
json "encoding/json/v2"
)
b, err := json.Marshal(cfg, v1.FormatDurationAsNano(true))
// {"timeout":1500000000} err=<nil>
json.Unmarshal(data, &cfg, v1.FormatDurationAsNano(true)) reads the integer back as 1.5s. If you’d rather send strings like "1.5s", give the field a named type with its own marshal methods.
Code written against the experiment
If you tried v2 under GOEXPERIMENT=jsonv2 on 1.25 or 1.26, re-check it on 1.27. The release notes list the removals: the format and unknown tag options, the DiscardUnknownMembers option and the SkipFunc sentinel error. The inline tag was renamed to embed, and the behavior of the string tag option and MatchCaseInsensitiveNames changed. The rename is the dangerous one, because the old spelling fails silently. A jsontext.Value field tagged json:",inline" compiles and runs on go1.27.3 without an error. On unmarshal the extra members are dropped. On marshal the value comes out nested under the field name:
embed: id=1 extra={"x":true,"y":[1,2]} err=<nil>
inline: id=1 extra="null" err=<nil>
inline marshal: {"id":2,"Extra":{"z":1}} err=<nil>
The embed line is the correct behavior: the unknown members x and y land in the catch-all field. Grep your codebase for ,inline before upgrading.
Options replace tag soup
The change I like most has nothing to do with speed. In v1, everything was a struct tag or a global, and anything you couldn’t express as a tag you couldn’t express at all. v2 makes options first-class function arguments that you pass to Marshal and Unmarshal directly. The package reference lists the full set.
b, err := json.Marshal(u,
json.FormatNilSliceAsNull(true), // keep v1 null-for-nil
json.Deterministic(true), // stable map key ordering
jsontext.WithIndent(" "), // pretty-print
)
That Deterministic(true) option is a small quality-of-life win worth calling out: it guarantees identical inputs produce identical output bytes, which makes golden-file tests and content hashing reliable without you sorting maps by hand. You can bundle options once and reuse them:
prettyV1 := json.JoinOptions(
json.FormatNilSliceAsNull(true),
json.FormatNilMapAsNull(true),
jsontext.WithIndent(" "),
)
out, _ := json.Marshal(payload, prettyV1)
The struct-tag vocabulary grew too. The most useful new tag is omitzero, which finally fixes the ancient confusion around omitempty:
type Event struct {
Name string `json:"name"`
Start time.Time `json:"start,omitzero"` // dropped when the zero Time
Tags []string `json:"tags,omitempty"` // dropped when empty JSON (null, "", {}, [])
}
Marshaling Event{Name: "launch"} on go1.27.3 gives {"name":"launch"}, with no zero timestamp.
omitempty in v1 was notorious for not omitting a zero time.Time (because a struct is never “empty” by its rule). omitzero checks the Go zero value (or an IsZero() method if your type has one), which is almost always what people meant in the first place. If you’ve ever shipped "start":"0001-01-01T00:00:00Z" into a JSON response by accident, this tag is for you.
Streaming and the O(n²) trap
The headline performance number is unmarshal speed, but the more interesting fix is structural. In v1, if a custom type implemented MarshalJSON, encoding a large slice of that type could degrade to O(n²): each element’s MarshalJSON allocated a fresh []byte, which then got re-parsed and re-copied into the parent buffer. Nest that a couple of levels deep and throughput falls off a cliff.
v2 adds streaming custom-marshaler interfaces that write directly into the shared encoder:
// Old, allocation-heavy:
// func (t T) MarshalJSON() ([]byte, error)
//
// New, streams into the parent encoder:
func (t T) MarshalJSONTo(enc *jsontext.Encoder) error {
return enc.WriteToken(jsontext.String(t.value))
}
If you’d rather not add methods to a type, v2 also takes function-based marshalers registered per type through json.WithMarshalers. Those helpers lean on Go generics so you get a type-safe func(T) handler instead of the old interface{} juggling. For bulk output you can drive the encoder yourself and avoid building a giant in-memory value at all:
import (
json "encoding/json/v2"
"encoding/json/jsontext"
)
func writeAll(w io.Writer, users []User) error {
enc := jsontext.NewEncoder(w)
for _, u := range users {
if err := json.MarshalEncode(enc, u); err != nil {
return err
}
}
return nil
}
The decode side mirrors it with json.UnmarshalDecode over a jsontext.Decoder, which pairs naturally with a range loop the way Go’s iterators do: read one value, process it, discard it, without holding the whole document in memory. Fed the stream {"id":1} {"id":2} {"id":3}, a for loop around UnmarshalDecode decodes the three values one at a time and stops cleanly on io.EOF. The Go team reported that in Kubernetes’ kube-openapi, recursive parsing inside UnmarshalJSON methods was a major cost, and switching to the streaming UnmarshalJSONFrom “improved performance by orders of magnitude.” That’s the kind of gain you only get from fixing the algorithmic shape of the problem, and no amount of parser tuning would have matched it.
Benchmarking it yourself
This post doesn’t include its own speed numbers. The snippets above ran on the Go Playground, a shared sandbox that’s fine for checking behavior and useless for timing. The “up to 10x” figure comes from the Go team’s own benchmarks, so treat it as reported, not measured. The same post puts Marshal roughly at parity with v1, “sometimes slightly faster, but other times slightly slower”. The big wins are on the unmarshal path, where the new parser does far less work.
Don’t take any single benchmark on faith, the Go team’s included. Here’s a harness you can drop into your own repo and run against your actual payloads, which is the only benchmark worth trusting:
package bench
import (
"os"
"testing"
json "encoding/json/v2"
)
func BenchmarkUnmarshal(b *testing.B) {
data, err := os.ReadFile("testdata/payload.json") // your real data
if err != nil {
b.Fatal(err)
}
b.ReportAllocs()
for b.Loop() {
var out []User
if err := json.Unmarshal(data, &out); err != nil {
b.Fatal(err)
}
}
}
# Go 1.27: v2 engine (also what plain encoding/json now runs on)
go test -bench=Unmarshal -benchmem -count=10 ./bench/ > new.txt
# the original v1 engine, for comparison (swap the import to "encoding/json" first)
GOEXPERIMENT=nojsonv2 go test -bench=Unmarshal -benchmem -count=10 ./bench/ > old.txt
benchstat old.txt new.txt
On 1.27 the interesting comparison is engine against engine. Plain encoding/json already sits on the v2 implementation, so a v1-import benchmark without the opt-out flag mostly measures the new code twice. Your mileage depends heavily on the shape of your data. Documents with lots of small objects and string-heavy payloads tend to show the largest gap, while a handful of big numeric arrays will show less.
A safe migration plan
The good news is that v2 is designed for gradual adoption. Since Go 1.27, v1 runs on top of the v2 implementation, and the two import paths coexist. The announcement says that while select parts of v1 may be deprecated over time, “the package as a whole will never be deprecated,” and the 1.27 notes add that “users are not required to migrate.” You don’t have to flip everything at once. Here’s the order I’d follow:
- Upgrade the toolchain in CI before prod. On 1.27 your v1 code keeps its behavior, so the usual breakage is tests that assert on exact error strings, since the notes warn that error message text may differ. If something deeper breaks,
GOEXPERIMENT=nojsonv2buys time while you file an issue. - Move one package at a time to
encoding/json/v2. Run its tests against the new import. Most failures will be golden-file or response-body assertions catching the nil-slice and case-sensitivity changes, plus thetime.Durationerrors. That’s your blast-radius report, for free. - Fix contracts, not symptoms. Where a test breaks because a nil slice now encodes as
[], decide which representation your API actually promises. Usually[]is correct and the test was wrong; occasionally a client depends onnulland you setFormatNilSliceAsNull(true)at that boundary. - Add
case:ignorewhere upstream casing is loose. Audit every place you unmarshal third-party JSON and tag the fields whose casing you don’t control. - Adopt
omitzeroin place of theomitempty-on-a-struct workarounds you’ve accumulated. - Leave the streaming interfaces for later. They’re an optimization you can defer safely. Convert the one or two hot paths that profiling flags, and leave the rest on plain
Marshal.
If you build data-heavy services, this is the same performance-versus-safety tradeoff conversation that plays out in Python land with msgspec versus Pydantic: a stricter, faster serializer that asks you to be explicit about your data’s shape. Go just happened to bake that upgrade into the standard library instead of a third-party package.
FAQ
Is Go json v2 stable and production-ready?
Yes, as of Go 1.27 (August 2026). encoding/json/v2 and encoding/json/jsontext are stable standard-library packages, and plain encoding/json runs on the same implementation. On Go 1.25 and 1.26 it was an experiment behind GOEXPERIMENT=jsonv2, and the API changed during that period: the format tag option was removed and inline became embed. So code written against the experiment needs a re-check on 1.27.
What’s the difference between encoding/json and encoding/json/v2?
Same core API (Marshal/Unmarshal), but v2 has stricter, safer defaults (rejects duplicate keys and invalid UTF-8, matches field names case-sensitively), encodes nil slices/maps as []/{} instead of null, refuses to guess a time.Duration encoding, adds first-class option arguments, and introduces the omitzero tag. On Go 1.27 both packages share the faster engine; the v1 import keeps the old defaults on top of it.
How much faster is Go json v2?
The Go team’s benchmarks show unmarshaling up to 10x faster than the old v1 engine, driven by a more efficient parser. Marshaling is about the same speed as v1. The gains depend on your data shape, so benchmark your own payloads rather than trusting a single headline number.
Do I need to rewrite my structs to use json v2?
No. Standard v1 struct tags keep working. You only touch code where a changed default affects your output: restoring null for nil slices at a specific boundary, adding case:ignore for loosely-cased upstreams, swapping omitempty for omitzero, or passing FormatDurationAsNano(true) where structs carry a time.Duration. Everything else is a recompile.
Can I use encoding/json/v2 on older Go versions?
On Go 1.27 or newer it’s built in. On Go 1.25 and 1.26 it needs GOEXPERIMENT=jsonv2, and you get the experimental API, which differs from the stable one in places. Go 1.24 and older have no stdlib route. The standalone github.com/go-json-experiment/json module now declares go 1.26 and mirrors the stdlib package, so upgrading the toolchain is the practical answer.
Sources
- A new experimental Go API for JSON — The Go Blog — the official announcement, rationale, and behavior changes
- encoding/json/v2 — Go Packages — full API reference for functions, options, and struct tags
- encoding/json/jsontext — Go Packages — the syntactic streaming layer
- encoding/json — Go Packages — the 16 documented v1/v2 differences and the v1 options (
FormatDurationAsNanoand friends) - Go 1.27 Release Notes — json/v2 goes stable, v1 moves onto the v2 engine,
nojsonv2opt-out, removed and renamed tag options - Go 1.25 Release Notes — where
GOEXPERIMENT=jsonv2first appeared - go-json-experiment/json — GitHub — the upstream where v2 was developed, now a mirror of the stdlib package
Bottom line
json/v2 is the rare standard-library change that’s both faster and safer, and the migration cost is mostly “run your tests and read the diffs.” The performance is a nice bonus; the real value is that the defaults finally match what most Go developers meant all along: no more null slices leaking into frontends, no more silently accepted duplicate keys, and case-insensitive matching stops quietly papering over schema mismatches. Go 1.27 already moved your v1 code onto the new engine. The remaining work is opting into the new defaults one package at a time, starting with a grep for time.Duration fields and leftover ,inline tags.