Back to Scaling Go applications guides

Go JSON v2: Stricter Defaults and a Measured Migration

Stanley Ulili
Updated on November 16, 2026

An API can return valid JSON and still surprise its consumers. A missing slice may become null where a frontend expects an array. Duplicate member names can produce different interpretations across services. A field with unexpected capitalization may be accepted by one decoder and ignored by another.

Go's encoding/json/v2⁠ changes several of those defaults while introducing a more flexible API. The Go project's current announcement identifies the new packages as stable in Go 1.27. Adopting the new API is also a decision about the application's wire behavior. A successful compilation does not establish compatibility with existing clients.

This guide explains the important behavioral differences, the syntax and semantic layers underneath the rewrite, and a migration approach that keeps performance work separate from contract changes.

The JSON boundary is an application contract

JSON connects programs that may have different type systems and parser behavior. A Go slice, a JavaScript array, and a database field can all represent related data while assigning different meanings to absence, emptiness, and null.

For a new API, an empty list is often a convenient representation of no results. For an existing API, however, clients may already use null to indicate that a field is unknown or unavailable. Changing the representation can therefore be either an improvement or a breaking change, depending on the contract.

Comparison of collection fields serialized by the original and new JSON packages

The same Go value can produce a different JSON representation when the package defaults change.

This makes serialization part of observable application behavior. Tests that only inspect the Go value before encoding do not cover the entire boundary. Tests should also inspect the response shape that consumers receive and the inputs that the service accepts.

The relevant compatibility question is not whether two packages expose similarly named functions. It is whether their outputs, errors, and field-matching rules agree on the data the application actually uses.

Nil collections become empty collections by default

For ordinary slices such as []string, v1 marshals a nil value as JSON null. V2 defaults to an empty JSON array. A nil map similarly becomes an empty object rather than null.

This can simplify a frontend that wants to iterate over a list without a separate null check. It does not eliminate the need to model absence deliberately. If null carries a distinct meaning, preserve it through the appropriate options or type design instead of assuming the new default expresses the same contract.

Do not generalize the slice rule to every special representation. Byte slices, custom marshalers, pointers, and fields with formatting options have their own behavior. Evaluate the concrete field types in the API rather than treating all Go collections as interchangeable.

For migration fixtures, include nil, allocated-but-empty, and nonempty values. Those states can look similar in application logic while taking different paths through serialization. They are especially important for persisted JSON and clients generated from a schema.

Duplicate names create ambiguous input

Consider an object that contains the same member name twice, with different values. A parser might retain the first value, retain the last, merge information, or reject the object. If two services interpret the same bytes differently, validation and use can diverge.

Duplicate role member accepted by v1 and rejected by v2 in the comparison

Rejecting a duplicate member removes an ambiguity before application code relies on the decoded result.

V2 rejects duplicate names by default. This is useful at service boundaries where one component validates a request and another consumes it. It narrows the set of inputs whose meaning depends on a parser-specific convention.

Rejection should still flow through normal error handling. A decoder reporting an error does not necessarily leave a partially populated destination safe to use. The application should avoid authorizing actions or persisting data from a value produced by a failed decode.

The change also deserves a compatibility test. Some existing producers may emit duplicates accidentally. Finding those producers during a comparison phase is easier than discovering them only after a production endpoint starts returning errors.

Stricter syntax does not mean every field is validated

V2 also rejects invalid UTF-8 by default, where the original behavior can replace invalid bytes in strings. Preserving an invalid byte sequence and silently changing it are both consequential choices for systems that compare or store values.

Behavior summary highlighting duplicate-name and invalid-UTF-8 rejection

Stricter syntax reduces ambiguity, while application-specific validation remains a separate responsibility.

Field matching changes as well. V1 accepts case-insensitive matches to struct field names, while v2 defaults to case-sensitive matching. A client sending the wrong capitalization can therefore stop populating a field.

Unknown members are still ignored by default. Case sensitivity alone does not turn a struct decoder into a complete request-schema validator. If the application requires unknown members to produce an error, the relevant v2 option is RejectUnknownMembers.

This combination can otherwise produce a subtle failure: a wrongly capitalized field becomes unknown, gets ignored, and leaves the Go field at its zero value. The input may decode without the application receiving the value the caller intended. Check required fields and domain constraints after decoding.

The original API remains available

The rewrite does not require every Go program to replace its imports. The original encoding/json remains covered by Go's compatibility commitments. Go 1.27 uses the new implementation beneath familiar v1 operations while preserving their compatibility behavior.

Original API implemented through the new engine with compatibility options

An implementation upgrade and a change to public defaults are separate decisions.

That separation gives existing applications a useful sequence. Upgrade the supported Go toolchain, run the normal test suite, and measure the existing application before changing JSON behavior. This establishes a baseline for the new engine under the old API.

It also keeps regression analysis simpler. If toolchain and serialization defaults change together, a failure has more possible causes. Separating them makes it easier to determine whether an issue comes from application assumptions, a behavioral option, or an unrelated upgrade.

The official migration guide documents jsonv1.DefaultOptionsV1() as a compatibility starting point for calls through the v2 API. Later options can override individual compatibility choices. That permits a gradual transition rather than requiring every endpoint to adopt all new defaults at once.

Syntax and Go-value mapping are different layers

The implementation separates JSON syntax from the mapping between JSON and Go values. encoding/json/jsontext⁠ handles tokens, values, encoding, and decoding at the grammar level. The v2 package handles marshaling and unmarshaling Go values.

Architecture diagram separating JSON syntax processing from Go-value mapping

The lower layer handles JSON structure, while the upper layer assigns that structure to Go values.

This makes the API easier to reason about for work that does not need a full Go object model. A component may need to inspect or transform a stream of JSON tokens without decoding the entire input into reflected structs.

The separation also supports more capable custom serialization. The original MarshalJSON and UnmarshalJSON interfaces exchange complete byte representations, which can require buffering and additional parsing. Streaming-oriented interfaces can operate through an encoder or decoder instead.

That does not make every use of JSON automatically streaming or allocation-free. The chosen interface and the application's own processing still determine whether a complete value must remain in memory. The architectural improvement is that token-level processing no longer has to be awkwardly mixed with Go-value conversion.

Reader and writer APIs make boundaries explicit

V2 includes operations such as MarshalWrite and UnmarshalRead, alongside byte-slice APIs. These make it easier to connect serialization to existing readers and writers without constructing an unnecessary intermediate buffer in application code.

API overview connecting JSON tokens, streaming operations, and Go values

Different entry points support different data-flow boundaries without requiring a single representation everywhere.

Options can be passed to individual calls, which helps when one boundary requires a compatibility behavior while another can use stricter defaults. A server does not need to choose one global rule for every internal and external use of JSON.

However, flexibility also creates configuration work. Decide where options are defined and how they are reviewed. If neighboring call sites use different rules unintentionally, the application can reintroduce the inconsistency the stricter defaults were meant to reduce.

Custom marshaling code deserves focused tests during migration. Include recursive values, embedded fields, and types with their own serialization methods. A package change can affect more than the top-level call even when the simple cases appear identical.

Output differences extend beyond nil values

The meaning of omitempty changes toward whether the encoded JSON value is empty, rather than simply following the old Go-value criteria. This deserves particular attention for fields where zero, false, an empty collection, and absence have different meanings.

Compatibility notes highlighting changes to omitempty behavior

Omission rules affect the shape of the response, not merely its formatting.

Map-key ordering is another migration concern. V2 does not sort map keys by default. JSON object member order is not normally a semantic property, but snapshot tests, signatures, caches, and byte-level comparisons may still depend on deterministic output. Where determinism is required, make it an explicit requirement and use the corresponding option.

Duration formatting also becomes explicit. A time.Duration previously encoded as a number of nanoseconds does not silently receive the same default representation in v2. Choose a supported format appropriate to the API and test it against the consumer's expectations.

Behavior notes identifying the need for an explicit time.Duration representation

A duration's representation belongs in the API contract rather than being inferred from its underlying integer type.

These differences illustrate why a broad import replacement is an incomplete migration plan. The code can compile while clients observe different omission, ordering, and formatting behavior. A useful fixture set includes both successful responses and the edge cases that exercise those rules.

Benchmark the operation the application performs

The Go announcement describes substantial unmarshaling improvements, with some benchmark workloads approaching an order-of-magnitude difference. Marshaling does not receive the same broad multiplier, and a service's total response time includes far more than serialization.

Measure the shapes and sizes the application handles: small request structs, large arrays, deeply nested values, custom types, and malformed input. Record allocation counts as well as elapsed time. A decoder that is faster for one data set may not dominate a workload whose cost lies in database access or business logic.

Existing third-party packages should be compared on those same inputs and semantics. A throughput number is less useful if one implementation accepts input another rejects or omits validation that the application requires. Standard-library support and portability can matter independently of the fastest single benchmark.

Keep compatibility and performance conclusions separate. An endpoint can benefit from stricter input handling without a dramatic speedup. Another can gain implementation performance while staying on v1 behavior. Neither outcome requires claiming that the whole API became ten times faster.

Compare before changing production behavior

The migration guide describes a jsonsplit approach that evaluates both implementations while continuing to return the v1 result. Differences can be reported without immediately changing the response visible to clients. Sampling limits the extra work when comparing every call would be too expensive.

Comparison path running v1 and v2 against the same data while retaining the original result

A comparison phase reveals behavior differences before the new result becomes the contract.

Use that evidence to group differences by cause: collection representation, member matching, omission, formatting, and errors. A difference is not automatically a bug. Some are the desired reason to migrate; others expose a client assumption that needs coordination.

Then move one boundary at a time. A new endpoint may adopt v2 defaults directly. An established endpoint may begin with v1 compatibility options and enable stricter rules after its producers and consumers are ready. Preserve representative fixtures so future changes can be checked against the same contract.

Comparison telemetry also needs an appropriate scope. Record the kind of difference and the relevant location without unnecessarily copying sensitive request bodies into logs. The aim is to understand behavior, not to create a second store of production payloads.

Final thoughts

Go's JSON rewrite offers stricter defaults, a cleaner distinction between syntax and Go-value conversion, and useful implementation improvements. The original API remains a supported path, so adoption can follow the needs of each application boundary.

Treat migration as a contract change supported by comparison evidence. Measure the existing engine first, test representative edge cases, and make defaults such as null handling, field matching, omission, and duration formatting explicit. That approach captures the benefits without assuming that a new import preserves every old response.

Got an article suggestion? Let us know
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.