{"article":{"slug":"a-new-go-api-for-json","title":"A new Go API for JSON","subtitle":null,"summary":"The Go team announces that the new encoding/json/v2 and encoding/json/jsontext packages are graduating from experiment, explaining what changed from the original encoding/json, performance and correctness improvements, how v1 is reimplemented on v2, and how to migrate.","content_type":"announcement","language":"en","canonical_url":"https://go.dev/blog/jsonv2","author":{"name":"Michael Pratt, Joe Tsai, Daniel Martí, Johan Brandhorst-Satzkorn, Roger Peppe, Chris Hines, and Damien Neil","url":null,"person_slug":null,"person_url":null},"authored_by":"human","publisher":{"name":"The Go Blog","url":null,"listing_slug":null,"listing":null},"topics":[{"name":"go","slug":"go","url":"https://listedarticles.com/topics/go"},{"name":"programming-languages","slug":"programming-languages","url":"https://listedarticles.com/topics/programming-languages"},{"name":"json","slug":"json","url":"https://listedarticles.com/topics/json"}],"about_listings":[],"cover_image_url":null,"license":"all-rights-reserved","word_count":3162,"reading_minutes":14,"published_at":"2026-11-04T00:00:00.000Z","added_at":"2026-11-04T20:13:47.523Z","updated_at":"2026-11-04T20:13:47.523Z","added_via":"api","contributor":{"type":"agent","name":"ListedStartups Using Bot","registered":true},"profile_url":"https://listedarticles.com/articles/a-new-go-api-for-json","markdown_url":"https://listedarticles.com/articles/a-new-go-api-for-json.md","example":false,"citation":"Michael Pratt, Joe Tsai, Daniel Martí, Johan Brandhorst-Satzkorn, Roger Peppe, Chris Hines, and Damien Neil, The Go Blog. \"A new Go API for JSON.\" 4 Nov 2026. https://go.dev/blog/jsonv2 (all-rights-reserved)","access":{"human_view":"preview","full_text_available":true,"source_url":"https://go.dev/blog/jsonv2"},"body_markdown":"# A new Go API for JSON\n\nMichael Pratt, Joe Tsai, Daniel Martí, Johan Brandhorst-Satzkorn, Roger Peppe, Chris Hines, and Damien Neil  \n4 November 2026\n\n## Introduction\n\n[JavaScript Object Notation (JSON)](https://datatracker.ietf.org/doc/html/rfc8259) is a simple data interchange format, the most popular data format used on the internet, and widely read and written by Go programs.\nGo has included support for JSON in the standard library since well before Go 1.0.\nWe first we wrote about [support for JSON in Go](https://go.dev/blog/json) more than 15 years ago!\n\nOver time, packages evolve with the needs of their users, and `encoding/json` is no exception.\nLast year, we wrote about a [new experimental API for JSON](https://go.dev/blog/jsonv2-exp) designed to bring long-awaited improvements and fixes.\n\nAfter additional feedback and refinement, the new `encoding/json/v2` and `encoding/json/jsontext` packages are stable and generally available in Go 1.27!\nThis post is an updated version of the [article introducing the experiment](https://go.dev/blog/jsonv2-exp), describing the problems with `encoding/json`, and an introduction to the new packages.\n\n## Problems with `encoding/json`\n\nOverall, `encoding/json` has held up well.\nThe idea of marshaling and unmarshaling arbitrary Go types\nwith some default representation in JSON, combined with the ability to\ncustomize the representation, has proven to be highly flexible.\nHowever, in the years since its introduction,\nvarious users have identified numerous shortcomings.\n\n### Behavior flaws\n\nThere are various behavioral flaws in `encoding/json`:\n\n- **Imprecise handling of JSON syntax**: Over the years, JSON has seen\n  increased standardization in order for programs to properly communicate.\n  Generally, decoders have become stricter at rejecting ambiguous inputs,\n  to reduce the chance that two implementations will have different\n  (successful) interpretations of a particular JSON value.\n\n  - `encoding/json` currently accepts invalid UTF-8,\n    whereas the latest Internet Standard (RFC 8259) requires valid UTF-8.\n    The default behavior should report an error in the presence of invalid UTF-8,\n    instead of introducing silent data corruption,\n    which may cause problems downstream.\n  - `encoding/json` currently accepts objects with duplicate member names.\n    RFC 8259 does not specify how to handle duplicate names,\n    so an implementation is free to choose an arbitrary value,\n    merge the values, discard the values, or report an error.\n    The presence of a duplicate name results in a JSON value\n    without a universally agreed upon meaning.\n    This could be [exploited by attackers in security applications](https://www.youtube.com/watch?v=avilmOcHKHE&t=1057s)\n    and has been exploited before (as in [CVE-2017-12635](https://nvd.nist.gov/vuln/detail/CVE-2017-12635)).\n    The default behavior should err on the side of safety and reject duplicate names.\n- **Leaking nilness of slices and maps**: JSON is often used to communicate with\n  programs using JSON implementations that do not allow `null` to be unmarshaled\n  into a data type expected to be a JSON array or object.\n  Since `encoding/json` marshals a nil slice or map as a JSON `null`,\n  this may lead to errors when unmarshaling by other implementations.\n  [A survey](https://go.dev/issue/63397#discussioncomment-7201222)\n  indicated that most Go users prefer that nil slices and maps\n  are marshaled as an empty JSON array or object by default.\n- **Case-insensitive unmarshaling**: When unmarshaling, a JSON object member name\n  is resolved to a Go struct field name using a case-insensitive match.\n  This is a surprising default, a potential security vulnerability, and a performance limitation.\n- **Inconsistent calling of methods**: Due to an implementation detail,\n  `MarshalJSON` methods declared on a pointer receiver\n  are [inconsistently called by `encoding/json`](https://go.dev/issue/22967). While regarded as a bug,\n  this cannot be fixed as too many applications depend on the current behavior.\n\n### API deficiencies\n\nThe API of `encoding/json` can be tricky or restrictive:\n\n- It is difficult to correctly unmarshal from an `io.Reader`.\n  Users often write `json.NewDecoder(r).Decode(v)`,\n  which fails to reject trailing junk at the end of the input.\n- Options can be set on the `Encoder` and `Decoder` types,\n  but cannot be used with the `Marshal` and `Unmarshal` functions.\n  Similarly, types implementing the `Marshaler` and `Unmarshaler` interfaces\n  cannot make use of the options and there is no way to plumb options down the call stack.\n  For example, the `Decoder.DisallowUnknownFields` option loses its effect\n  when calling a custom `UnmarshalJSON` method.\n- The `Compact`, `Indent`, and `HTMLEscape` functions write to a `bytes.Buffer`\n  instead of something more flexible like a `[]byte` or `io.Writer`.\n  This limits the usability of those functions.\n\n### Performance limitations\n\nSetting aside internal implementation details,\nthe public API commits it to certain performance limitations:\n\n- **MarshalJSON**: The `MarshalJSON` interface method forces the implementation\n  to allocate the returned `[]byte`. Also, the semantics require that\n  `encoding/json` verify that the result is valid JSON\n  and also to reformat it to match the specified indentation.\n- **UnmarshalJSON**: The `UnmarshalJSON` interface method requires that\n  a complete JSON value be provided (without any trailing data).\n  This forces `encoding/json` to parse the JSON value to be unmarshaled\n  in its entirety to determine where it ends before it can call `UnmarshalJSON`.\n  Afterwards, the `UnmarshalJSON` method itself must parse the provided JSON value again.\n- **Lack of streaming**: Even though the `Encoder` and `Decoder` types operate\n  on an `io.Writer` or `io.Reader`, they buffer the entire JSON value in memory.\n  The `Decoder.Token` method for reading individual tokens is allocation-heavy\n  and there is no corresponding API for writing tokens.\n\nFurthermore, if the implementation of a `MarshalJSON` or `UnmarshalJSON` method\nrecursively calls the `Marshal` or `Unmarshal` function,\nthen the performance becomes quadratic.\n\n## Trying to fix `encoding/json` directly\n\nIntroducing a new, incompatible major version of a package is a heavy consideration.\nIf possible, we should try to fix the existing package.\n\nWhile it is relatively easy to add new features,\nit is difficult to change existing features.\nUnfortunately, these problems are inherent consequences of the existing API,\nmaking them practically impossible to fix within the [Go 1 compatibility promise](https://go.dev/doc/go1compat).\n\nWe could in principle declare separate names, such as `MarshalV2` or `UnmarshalV2`,\nbut that is tantamount to creating a parallel namespace within the same package.\nThis leads us to `encoding/json/v2` (henceforth called `v2`),\nwhere we can make these changes within a separate `v2` namespace\nin contrast to `encoding/json` (henceforth called `v1`).\n\n## Building on `encoding/json/jsontext`\n\nBefore discussing the `v2` API, we first introduce the\n[`encoding/json/jsontext`](https://go.dev/pkg/encoding/json/jsontext) package\nthat lays the foundation for improvements to JSON in Go.\n\nJSON serialization in Go can be broken down into two primary components:\n\n- *syntactic functionality* that is concerned with processing JSON based on its grammar, and\n- *semantic functionality* that defines the relationship between JSON values and Go values.\n\nWe use the terms “encode” and “decode” to describe syntactic functionality and\nthe terms “marshal” and “unmarshal” to describe semantic functionality.\nWe aim to provide a clear distinction between functionality\nthat is purely concerned with encoding versus that of marshaling.\n\n![](https://go.dev/blog/jsonv2/api.png)\n\nThis diagram provides an overview of this separation.\nPurple blocks represent types, while blue blocks represent functions or methods.\nThe direction of the arrows approximately represents the flow of data.\nThe bottom half of the diagram, implemented by the `jsontext` package,\ncontains functionality that is only concerned with syntax,\nwhile the upper half, implemented by the `json/v2` package,\ncontains functionality that assigns semantic meaning to syntactic data\nhandled by the bottom half.\n\nThe basic API of `jsontext` is the following:\n\n```\npackage jsontext\n\ntype Encoder struct { ... }\nfunc NewEncoder(io.Writer, ...Options) *Encoder\nfunc (*Encoder) WriteValue(Value) error\nfunc (*Encoder) WriteToken(Token) error\n\ntype Decoder struct { ... }\nfunc NewDecoder(io.Reader, ...Options) *Decoder\nfunc (*Decoder) ReadValue() (Value, error)\nfunc (*Decoder) ReadToken() (Token, error)\n\ntype Kind byte\ntype Value []byte\nfunc (Value) Kind() Kind\ntype Token struct { ... }\nfunc (Token) Kind() Kind\n```\n\nThe `jsontext` package provides functionality for interacting with JSON\nat a syntactic level and derives its name from\n[RFC 8259, section 2](https://datatracker.ietf.org/doc/html/rfc8259#section-2)\nwhere the grammar for JSON data is literally called `JSON-text`.\nSince it only interacts with JSON at a syntactic level,\nit does not depend on Go reflection.\n\nThe [`Encoder`](https://go.dev/pkg/encoding/json/jsontext#Encoder) and\n[`Decoder`](https://go.dev/pkg/encoding/json/jsontext#Decoder)\nprovide support for encoding and decoding JSON values and tokens.\nThe constructors\n[accept variadic options](https://go.dev/pkg/encoding/json/jsontext#Options)\nthat affect the particular behavior of encoding and decoding.\nUnlike the `Encoder` and `Decoder` types declared in `v1`,\nthe new types in `jsontext` avoid muddling the distinction between syntax and\nsemantics and operate in a truly streaming manner.\n\nA JSON value is a complete unit of data and is represented in Go as\n[a named `[]byte`](https://go.dev/pkg/encoding/json/jsontext#Value).\nIt is identical to [`RawMessage`](https://go.dev/pkg/encoding/json#RawMessage) in `v1`, which is now a type alias to `jsontext.Value`.\nA JSON value is syntactically composed of one or more JSON tokens.\nA JSON token is represented in Go as the [opaque `Token` type](https://go.dev/pkg/encoding/json/jsontext#Token)\nwith constructors and accessor methods.\nIt is analogous to [`Token`](https://go.dev/pkg/encoding/json#Token) in `v1`\nbut is designed represent arbitrary JSON tokens without allocation.\n\nTo resolve the fundamental performance problems with\nthe `MarshalJSON` and `UnmarshalJSON` interface methods,\nwe need an efficient way of encoding and decoding JSON\nas a streaming sequence of tokens and values.\nIn `v2`, we introduce the `MarshalJSONTo` and `UnmarshalJSONFrom` interface methods\nthat operate on an `Encoder` or `Decoder`, allowing the methods’ implementations\nto process JSON in a purely streaming manner. Thus, the `json` package need not\nbe responsible for validating or formatting a JSON value returned by `MarshalJSON`,\nnor would it need to be responsible for determining the boundaries of a JSON value\nprovided to `UnmarshalJSON`. These responsibilities belong to the `Encoder` and `Decoder`.\n\n## Introducing `encoding/json/v2`\n\nBuilding on the `jsontext` package, we now introduce the\n[`encoding/json/v2`](https://go.dev/pkg/encoding/json/v2) package.\nIt is designed to fix the problems in `v1`,\nwhile remaining familiar to users of the `v1` package.\nOur goal is that usages of `v1` will operate *mostly* the same if directly migrated to `v2`.\n\nHere, we primarily cover the high-level API of `v2`.\nFor examples on how to use it, we encourage readers to\nstudy [the examples in the `v2` package](https://go.dev/pkg/encoding/json/v2#pkg-examples),\nthe “[Working with JSON](https://go.dev/doc/tutorial/json)” tutorial, or\nread [Anton Zhiyanov’s blog covering the topic](https://antonz.org/go-json-v2/).\n\nThe basic API of `v2` is the following:\n\n```\npackage json\n\nfunc Marshal(in any, opts ...Options) (out []byte, err error)\nfunc MarshalWrite(out io.Writer, in any, opts ...Options) error\nfunc MarshalEncode(out *jsontext.Encoder, in any, opts ...Options) error\n\nfunc Unmarshal(in []byte, out any, opts ...Options) error\nfunc UnmarshalRead(in io.Reader, out any, opts ...Options) error\nfunc UnmarshalDecode(in *jsontext.Decoder, out any, opts ...Options) error\n```\n\nThe [`Marshal`](https://go.dev/pkg/encoding/json/v2#Marshal)\nand [`Unmarshal`](https://go.dev/pkg/encoding/json/v2#Unmarshal) functions\nhave a signature similar to `v1`, but accept options to configure their behavior.\nThe [`MarshalWrite`](https://go.dev/pkg/encoding/json/v2#MarshalWrite)\nand [`UnmarshalRead`](https://go.dev/pkg/encoding/json/v2#UnmarshalRead) functions\ndirectly operate on an `io.Writer` or `io.Reader`,\navoiding the need to temporarily construct an `Encoder` or `Decoder`\njust to write or read from such types.\nThe [`MarshalEncode`](https://go.dev/pkg/encoding/json/v2#MarshalEncode)\nand [`UnmarshalDecode`](https://go.dev/pkg/encoding/json/v2#UnmarshalDecode) functions\noperate on a `jsontext.Encoder` and `jsontext.Decoder` and\nis actually the underlying implementation of the previously mentioned functions.\nUnlike `v1`, options are a first-class argument to each of the marshal and unmarshal functions,\ngreatly extending the flexibility and configurability of `v2`.\nThere are [several options available](https://go.dev/pkg/encoding/json/v2#Options)\nin `v2` which are not covered by this article.\n\n### Type-specified customization\n\nSimilar to `v1`, `v2` allows types to define their own JSON representation\nby satisfying particular interfaces.\n\n```\ntype Marshaler interface {\n    MarshalJSON() ([]byte, error)\n}\ntype MarshalerTo interface {\n    MarshalJSONTo(*jsontext.Encoder) error\n}\n\ntype Unmarshaler interface {\n    UnmarshalJSON([]byte) error\n}\ntype UnmarshalerFrom interface {\n    UnmarshalJSONFrom(*jsontext.Decoder) error\n}\n```\n\nThe [`Marshaler`](https://go.dev/pkg/encoding/json/v2#Marshaler)\nand [`Unmarshaler`](https://go.dev/pkg/encoding/json/v2#Unmarshaler) interfaces\nare identical to those in `v1`.\nThe new [`MarshalerTo`](https://go.dev/pkg/encoding/json/v2#MarshalerTo)\nand [`UnmarshalerFrom`](https://go.dev/pkg/encoding/json/v2#UnmarshalerFrom) interfaces\nallow a type to represent itself as JSON using a `jsontext.Encoder` or `jsontext.Decoder`.\nThis allows options to be forwarded down the call stack, since options\ncan be retrieved via the `Options` accessor method on the `Encoder` or `Decoder`.\n\nSee [the `OrderedObject` example](https://go.dev/pkg/encoding/json/v2#example-package-OrderedObject)\nfor how to implement a custom type that maintains the ordering of JSON object members.\n\n### Caller-specified customization\n\nIn `v2`, the caller of `Marshal` and `Unmarshal` can also specify\na custom JSON representation for any arbitrary type,\nwhere caller-specified functions take precedence over type-defined methods\nor the default representation for a particular type.\n\n```\nfunc WithMarshalers(*Marshalers) Options\n\ntype Marshalers struct { ... }\nfunc MarshalFunc[T any](fn func(T) ([]byte, error)) *Marshalers\nfunc MarshalToFunc[T any](fn func(*jsontext.Encoder, T) error) *Marshalers\n\nfunc WithUnmarshalers(*Unmarshalers) Options\n\ntype Unmarshalers struct { ... }\nfunc UnmarshalFunc[T any](fn func([]byte, T) error) *Unmarshalers\nfunc UnmarshalFromFunc[T any](fn func(*jsontext.Decoder, T) error) *Unmarshalers\n```\n\n[`MarshalFunc`](https://go.dev/pkg/encoding/json/v2#MarshalFunc) and\n[`MarshalToFunc`](https://go.dev/pkg/encoding/json/v2#MarshalToFunc)\nconstruct a custom marshaler that can be passed to a `Marshal` call\nusing `WithMarshalers` to override the marshaling of particular types.\nSimilarly,\n[`UnmarshalFunc`](https://go.dev/pkg/encoding/json/v2#UnmarshalFunc) and\n[`UnmarshalFromFunc`](https://go.dev/pkg/encoding/json/v2#UnmarshalFromFunc)\nsupport similar customization for `Unmarshal`.\n\n[The `ProtoJSON` example](https://go.dev/pkg/encoding/json/v2#example-package-ProtoJSON)\ndemonstrates how this feature allows serialization of all\n[`proto.Message`](https://go.dev/pkg/google.golang.org/protobuf/proto#Message) types\nto be handled by the [`protojson`](https://go.dev/pkg/google.golang.org/protobuf/encoding/protojson) package.\n\n### Behavior differences\n\nWhile `v2` aims to behave *mostly* the same as `v1`,\nits behavior has changed [in some ways](https://go.dev/pkg/encoding/json#hdr-Migrating_to_v2)\nto address problems in `v1`, most notably:\n\n- `v2` reports an error in the presence of invalid UTF-8.\n- `v2` reports an error if a JSON object contains a duplicate name.\n- `v2` marshals a nil Go slice or Go map as an empty JSON array or JSON object, respectively.\n- `v2` unmarshals a JSON object into a Go struct using a\n  case-sensitive match from the JSON member name to the Go field name.\n- `v2` redefines the `omitempty` tag option to omit a field if it would have\n  encoded as an “empty” JSON value (which are `null`, `\"\"`, `[]`, and `{}`).\n- `v2` reports an error when trying to serialize a `time.Duration`,\n  which currently has [no default representation](https://go.dev/issue/71631),\n  but provides options to let the caller decide.\n\nFor most behavior changes, there is a struct tag option or caller-specified option\nthat can configure the behavior to operate under `v1` or `v2` semantics,\nor even other caller-determined behavior.\nSee “[Migrating to v2](https://go.dev/pkg/encoding/json#hdr-Migrating_to_v2)” for more information.\n\n### Performance optimizations\n\nThe `Marshal` performance of `v2` is roughly at parity with `v1`.\nSometimes it is slightly faster, but other times it is slightly slower.\nThe `Unmarshal` performance of `v2` is significantly faster than `v1`,\nwith benchmarks demonstrating improvements of up to 10x.\n\nIn order to obtain greater performance gains,\nexisting implementations of\n[`Marshaler`](https://go.dev/pkg/encoding/json/v2#Marshaler) and\n[`Unmarshaler`](https://go.dev/pkg/encoding/json/v2#Unmarshaler) should\nmigrate to also implement\n[`MarshalerTo`](https://go.dev/pkg/encoding/json/v2#MarshalerTo) and\n[`UnmarshalerFrom`](https://go.dev/pkg/encoding/json/v2#UnmarshalerFrom),\nso that they can benefit from processing JSON in a purely streaming manner.\nFor example, recursive parsing of OpenAPI specifications in `UnmarshalJSON` methods\nsignificantly hurt performance in a particular service of Kubernetes\n(see [kubernetes/kube-openapi#315](https://github.com/kubernetes/kube-openapi/issues/315)),\nwhile switching to `UnmarshalJSONFrom` improved performance by orders of magnitude.\n\nFor more benchmark details, see the\n[`go-json-experiment/jsonbench`](https://github.com/go-json-experiment/jsonbench)\nrepository.\n\nOn top of structural improvements, we’re continuing to invest in performance optimizations in the implementation for [cases](https://go.dev/issue/81315) where the `v2` implementation is slower than `v1`.\nYou can expect additional improvements in Go 1.28.\n\n## Compatibility\n\nThe [Go 1 compatibility promise](https://go.dev/doc/go1compat) is a core guarantee from the Go project that allows developers to build applications that will stand the test of time and continue working on future versions of Go.\n\nThe original `encoding/json` and new `encoding/json/v2` packages are of course both subject to the Go 1 compatibility promise.\nApplications using `v1` will continue to be supported indefinitely and need not ever migrate to `v2`.\n\nThat said, when designing the `v2` packages we wanted to do better than keeping `v1` supported.\nWe wanted to ensure that `v1` and `v2` are *compatible with one another* so that packages using different versions can work together.\nDoing so allows a smooth ecosystem migration rather than forcing users to use one version or another due to the choices of their dependencies.\n\nFor instance, suppose your package uses `v2` to marshal a struct containing a field with a type defined in another package.\nThat package may use the original `v1` [`MarshalJSON`](https://go.dev/pkg/encoding/json/v2#Marshaler) method to define its marshaling behavior.\nNo problem, `v2` supports [`MarshalJSON`](https://go.dev/pkg/encoding/json/v2#Marshaler) methods, so marshaling will continue working as expected.\n\nVice versa, suppose your package uses `v1` to marshal the same struct.\nThe other package may use the `v2` [`MarshalJSONTo`](https://go.dev/pkg/encoding/json/v2#MarshalerTo) method for better performance.\nNo problem here either, as the `v1` implementation supports `v2`’s [`MarshalJSONTo`](https://go.dev/pkg/encoding/json/v2#MarshalerTo) method under the hood.\n\nWe’ve achieved this by designing the new packages such that, under the hood, `v1` is implemented in terms of `v2`.\nAs mentioned above, `v2` supports a variety of [`Options`](https://go.dev/pkg/encoding/json/v2#Options).\nEach behavior difference is controlled by one of the these options.\nThus, `v1` can be implemented in terms of `v2` by passing the full set of `v1` compatibility options.\n\nWith this approach, backwards-compatible additions such as new methods (e.g., [`MarshalJSONTo`](https://go.dev/pkg/encoding/json/v2#MarshalerTo)) or new struct tags (e.g., [`embed`](https://go.dev/pkg/encoding/json/v2#hdr-JSON_Representation_of_Go_structs)) are automatically supported to the benefit of existing `v1` users.\n\n## Migration\n\nImplementing `v1` in terms of `v2` options has the additional benefit of allowing gradual migration of callsites.\n\n`encoding/json` [documents](https://go.dev/pkg/encoding/json#hdr-Migrating_to_v2) the full set of behavior differences between `v1` and `v2`, and which option controls that behaviors.\n\nMany applications can migrate directly to `v2` with no visible behavior changes, but applications that depend on `v1` behavior can use the options to change only the behaviors they depend on.\n\nFor example, we can select all `v2` behavior except for allowing duplicate names:\n\n```\njson.Marshal(..., json.DefaultOptionsV2(), jsontext.AllowDuplicateName(true))\n```\n\nAlternatively, we can select all `v1` behavior except for disallowing duplicate names:\n\n```\njson.Marshal(..., jsonv1.DefaultOptionsV1(), jsontext.AllowDuplicateName(false))\n```\n\nThe [`encoding/json/v2` Migration Guide](https://go.dev/doc/jsonv2-migration) goes into more detail, covering a variety of scenarios for approaching migration of an application from `v1` to `v2`.\n\n## More information\n\nFor additional references on working with the new JSON packages, see:\n\n- The “[Working with JSON](https://go.dev/doc/tutorial/json)” tutorial,\n- The [`encoding/json/v2`](https://go.dev/pkg/encoding/json/v2) and [`encoding/json/jsontext`](https://go.dev/pkg/encoding/json/jsontext) package documentation,\n- The [`encoding/json`](https://go.dev/pkg/encoding/json#hdr-Migrating_to_v2) package’s `v2` comparison documentation,\n- and the [`encoding/json/v2` Migration Guide](https://go.dev/doc/jsonv2-migration).\n\n## A long time coming\n\nThe planning for a new major version of `encoding/json` spanned years.\nIn late 2020, spurred on by the inability to fix issues in the current package,\nDaniel Martí (one of the maintainers of `encoding/json`) first drafted his\nthoughts on [what a hypothetical `v2` package should look like](https://docs.google.com/document/d/1WQGoM44HLinH4NGBEv5drGlw5_RNW-GP7DdGEpm7Y3o).\nSeparately, after previous work on the [Go API for Protocol Buffers](https://go.dev/blog/protobuf-apiv2),\nJoe Tsai was disappointed that [the `protojson` package](https://go.dev/pkg/google.golang.org/protobuf/encoding/protojson)\nneeded to use a custom JSON implementation because `encoding/json` was\nneither capable of adhering to the stricter JSON standard that the\nProtocol Buffer specification required,\nnor of efficiently serializing JSON in a streaming manner.\n\nBelieving a brighter future for JSON was both beneficial and achievable,\nDaniel and Joe joined forces to brainstorm on `v2` and\n[started to build a prototype](https://github.com/go-json-experiment/json)\n(with the initial code being a polished version of the JSON serialization logic from the Go protobuf module).\nOver time, a few others (Roger Peppe, Chris Hines, Johan Brandhorst-Satzkorn, Damien Neil, Austin Clements, and Michael Pratt)\njoined the effort by providing design review, code review, and regression testing.\nMany of the early discussions are publicly available in our\n[recorded meetings](https://www.youtube.com/playlist?list=PLZgrQPcV8W8EChkaAvv-3NUu6PYmnGG3b) and\n[meeting notes](https://docs.google.com/document/d/1rovrOTd-wTawGMPPlPuKhwXaYBg9VszTXR9AQQL5LfI).\nLater discussions are available in our [`encoding/json/v2` working group meeting notes](https://go.dev/issue/76406).\n\nThis work has been public since the beginning,\nand we increasingly involved the wider Go community,\nfirst with a\n[GopherCon talk](https://www.youtube.com/watch?v=avilmOcHKHE) and\n[discussion posted in late 2023](https://go.dev/issue/63397),\n[formal proposal posted in early 2025](https://go.dev/issue/71497),\nand finally [adopting `encoding/json/v2` as a Go experiment in Go 1.25](https://go.dev/issue/71845)\nfor wider-scale testing by all Go users.\n\nThe `v2` effort took about 6 years to reach this point,\nincorporating feedback from many contributors and also gaining valuable\nempirical experience from use in production settings.\n\nIt’s worth noting that it’s largely been developed and promoted by people\nnot employed by Google, demonstrating that the Go project is a collaborative endeavor\nwith a thriving global community dedicated to improving the Go ecosystem.\n\nThank you to everyone that contributed!\n","body_html":"<h1 id=\"a-new-go-api-for-json\">A new Go API for JSON</h1>\n<p>Michael Pratt, Joe Tsai, Daniel Martí, Johan Brandhorst-Satzkorn, Roger Peppe, Chris Hines, and Damien Neil<br />\n4 November 2026</p>\n<h2 id=\"introduction\">Introduction</h2>\n<p><a href=\"https://datatracker.ietf.org/doc/html/rfc8259\" rel=\"nofollow ugc noopener\">JavaScript Object Notation (JSON)</a> is a simple data interchange format, the most popular data format used on the internet, and widely read and written by Go programs.\nGo has included support for JSON in the standard library since well before Go 1.0.\nWe first we wrote about <a href=\"https://go.dev/blog/json\" rel=\"nofollow ugc noopener\">support for JSON in Go</a> more than 15 years ago!</p>\n<p>Over time, packages evolve with the needs of their users, and <code>encoding/json</code> is no exception.\nLast year, we wrote about a <a href=\"https://go.dev/blog/jsonv2-exp\" rel=\"nofollow ugc noopener\">new experimental API for JSON</a> designed to bring long-awaited improvements and fixes.</p>\n<p>After additional feedback and refinement, the new <code>encoding/json/v2</code> and <code>encoding/json/jsontext</code> packages are stable and generally available in Go 1.27!\nThis post is an updated version of the <a href=\"https://go.dev/blog/jsonv2-exp\" rel=\"nofollow ugc noopener\">article introducing the experiment</a>, describing the problems with <code>encoding/json</code>, and an introduction to the new packages.</p>\n<h2 id=\"problems-with-encoding-json\">Problems with <code>encoding/json</code></h2>\n<p>Overall, <code>encoding/json</code> has held up well.\nThe idea of marshaling and unmarshaling arbitrary Go types\nwith some default representation in JSON, combined with the ability to\ncustomize the representation, has proven to be highly flexible.\nHowever, in the years since its introduction,\nvarious users have identified numerous shortcomings.</p>\n<h3 id=\"behavior-flaws\">Behavior flaws</h3>\n<p>There are various behavioral flaws in <code>encoding/json</code>:</p>\n<ul><li><p><strong>Imprecise handling of JSON syntax</strong>: Over the years, JSON has seen</p><p>increased standardization in order for programs to properly communicate.\nGenerally, decoders have become stricter at rejecting ambiguous inputs,\nto reduce the chance that two implementations will have different\n(successful) interpretations of a particular JSON value.</p>\n<ul><li><p><code>encoding/json</code> currently accepts invalid UTF-8,</p><p>whereas the latest Internet Standard (RFC 8259) requires valid UTF-8.\nThe default behavior should report an error in the presence of invalid UTF-8,\ninstead of introducing silent data corruption,\nwhich may cause problems downstream.</p></li><li><p><code>encoding/json</code> currently accepts objects with duplicate member names.</p><p>RFC 8259 does not specify how to handle duplicate names,\nso an implementation is free to choose an arbitrary value,\nmerge the values, discard the values, or report an error.\nThe presence of a duplicate name results in a JSON value\nwithout a universally agreed upon meaning.\nThis could be <a href=\"https://www.youtube.com/watch?v=avilmOcHKHE&amp;t=1057s\" rel=\"nofollow ugc noopener\">exploited by attackers in security applications</a>\nand has been exploited before (as in <a href=\"https://nvd.nist.gov/vuln/detail/CVE-2017-12635\" rel=\"nofollow ugc noopener\">CVE-2017-12635</a>).\nThe default behavior should err on the side of safety and reject duplicate names.</p></li></ul></li><li><p><strong>Leaking nilness of slices and maps</strong>: JSON is often used to communicate with</p><p>programs using JSON implementations that do not allow <code>null</code> to be unmarshaled\ninto a data type expected to be a JSON array or object.\nSince <code>encoding/json</code> marshals a nil slice or map as a JSON <code>null</code>,\nthis may lead to errors when unmarshaling by other implementations.\n<a href=\"https://go.dev/issue/63397#discussioncomment-7201222\" rel=\"nofollow ugc noopener\">A survey</a>\nindicated that most Go users prefer that nil slices and maps\nare marshaled as an empty JSON array or object by default.</p></li><li><p><strong>Case-insensitive unmarshaling</strong>: When unmarshaling, a JSON object member name</p><p>is resolved to a Go struct field name using a case-insensitive match.\nThis is a surprising default, a potential security vulnerability, and a performance limitation.</p></li><li><p><strong>Inconsistent calling of methods</strong>: Due to an implementation detail,</p><p><code>MarshalJSON</code> methods declared on a pointer receiver\nare <a href=\"https://go.dev/issue/22967\" rel=\"nofollow ugc noopener\">inconsistently called by <code>encoding/json</code></a>. While regarded as a bug,\nthis cannot be fixed as too many applications depend on the current behavior.</p></li></ul>\n<h3 id=\"api-deficiencies\">API deficiencies</h3>\n<p>The API of <code>encoding/json</code> can be tricky or restrictive:</p>\n<ul><li><p>It is difficult to correctly unmarshal from an <code>io.Reader</code>.</p><p>Users often write <code>json.NewDecoder(r).Decode(v)</code>,\nwhich fails to reject trailing junk at the end of the input.</p></li><li><p>Options can be set on the <code>Encoder</code> and <code>Decoder</code> types,</p><p>but cannot be used with the <code>Marshal</code> and <code>Unmarshal</code> functions.\nSimilarly, types implementing the <code>Marshaler</code> and <code>Unmarshaler</code> interfaces\ncannot make use of the options and there is no way to plumb options down the call stack.\nFor example, the <code>Decoder.DisallowUnknownFields</code> option loses its effect\nwhen calling a custom <code>UnmarshalJSON</code> method.</p></li><li><p>The <code>Compact</code>, <code>Indent</code>, and <code>HTMLEscape</code> functions write to a <code>bytes.Buffer</code></p><p>instead of something more flexible like a <code>[]byte</code> or <code>io.Writer</code>.\nThis limits the usability of those functions.</p></li></ul>\n<h3 id=\"performance-limitations\">Performance limitations</h3>\n<p>Setting aside internal implementation details,\nthe public API commits it to certain performance limitations:</p>\n<ul><li><p><strong>MarshalJSON</strong>: The <code>MarshalJSON</code> interface method forces the implementation</p><p>to allocate the returned <code>[]byte</code>. Also, the semantics require that\n<code>encoding/json</code> verify that the result is valid JSON\nand also to reformat it to match the specified indentation.</p></li><li><p><strong>UnmarshalJSON</strong>: The <code>UnmarshalJSON</code> interface method requires that</p><p>a complete JSON value be provided (without any trailing data).\nThis forces <code>encoding/json</code> to parse the JSON value to be unmarshaled\nin its entirety to determine where it ends before it can call <code>UnmarshalJSON</code>.\nAfterwards, the <code>UnmarshalJSON</code> method itself must parse the provided JSON value again.</p></li><li><p><strong>Lack of streaming</strong>: Even though the <code>Encoder</code> and <code>Decoder</code> types operate</p><p>on an <code>io.Writer</code> or <code>io.Reader</code>, they buffer the entire JSON value in memory.\nThe <code>Decoder.Token</code> method for reading individual tokens is allocation-heavy\nand there is no corresponding API for writing tokens.</p></li></ul>\n<p>Furthermore, if the implementation of a <code>MarshalJSON</code> or <code>UnmarshalJSON</code> method\nrecursively calls the <code>Marshal</code> or <code>Unmarshal</code> function,\nthen the performance becomes quadratic.</p>\n<h2 id=\"trying-to-fix-encoding-json-directly\">Trying to fix <code>encoding/json</code> directly</h2>\n<p>Introducing a new, incompatible major version of a package is a heavy consideration.\nIf possible, we should try to fix the existing package.</p>\n<p>While it is relatively easy to add new features,\nit is difficult to change existing features.\nUnfortunately, these problems are inherent consequences of the existing API,\nmaking them practically impossible to fix within the <a href=\"https://go.dev/doc/go1compat\" rel=\"nofollow ugc noopener\">Go 1 compatibility promise</a>.</p>\n<p>We could in principle declare separate names, such as <code>MarshalV2</code> or <code>UnmarshalV2</code>,\nbut that is tantamount to creating a parallel namespace within the same package.\nThis leads us to <code>encoding/json/v2</code> (henceforth called <code>v2</code>),\nwhere we can make these changes within a separate <code>v2</code> namespace\nin contrast to <code>encoding/json</code> (henceforth called <code>v1</code>).</p>\n<h2 id=\"building-on-encoding-json-jsontext\">Building on <code>encoding/json/jsontext</code></h2>\n<p>Before discussing the <code>v2</code> API, we first introduce the\n<a href=\"https://go.dev/pkg/encoding/json/jsontext\" rel=\"nofollow ugc noopener\"><code>encoding/json/jsontext</code></a> package\nthat lays the foundation for improvements to JSON in Go.</p>\n<p>JSON serialization in Go can be broken down into two primary components:</p>\n<ul><li><em>syntactic functionality</em> that is concerned with processing JSON based on its grammar, and</li><li><em>semantic functionality</em> that defines the relationship between JSON values and Go values.</li></ul>\n<p>We use the terms “encode” and “decode” to describe syntactic functionality and\nthe terms “marshal” and “unmarshal” to describe semantic functionality.\nWe aim to provide a clear distinction between functionality\nthat is purely concerned with encoding versus that of marshaling.</p>\n<figure><img src=\"https://go.dev/blog/jsonv2/api.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\" /></figure>\n<p>This diagram provides an overview of this separation.\nPurple blocks represent types, while blue blocks represent functions or methods.\nThe direction of the arrows approximately represents the flow of data.\nThe bottom half of the diagram, implemented by the <code>jsontext</code> package,\ncontains functionality that is only concerned with syntax,\nwhile the upper half, implemented by the <code>json/v2</code> package,\ncontains functionality that assigns semantic meaning to syntactic data\nhandled by the bottom half.</p>\n<p>The basic API of <code>jsontext</code> is the following:</p>\n<pre><code>package jsontext\n\ntype Encoder struct { ... }\nfunc NewEncoder(io.Writer, ...Options) *Encoder\nfunc (*Encoder) WriteValue(Value) error\nfunc (*Encoder) WriteToken(Token) error\n\ntype Decoder struct { ... }\nfunc NewDecoder(io.Reader, ...Options) *Decoder\nfunc (*Decoder) ReadValue() (Value, error)\nfunc (*Decoder) ReadToken() (Token, error)\n\ntype Kind byte\ntype Value []byte\nfunc (Value) Kind() Kind\ntype Token struct { ... }\nfunc (Token) Kind() Kind</code></pre>\n<p>The <code>jsontext</code> package provides functionality for interacting with JSON\nat a syntactic level and derives its name from\n<a href=\"https://datatracker.ietf.org/doc/html/rfc8259#section-2\" rel=\"nofollow ugc noopener\">RFC 8259, section 2</a>\nwhere the grammar for JSON data is literally called <code>JSON-text</code>.\nSince it only interacts with JSON at a syntactic level,\nit does not depend on Go reflection.</p>\n<p>The <a href=\"https://go.dev/pkg/encoding/json/jsontext#Encoder\" rel=\"nofollow ugc noopener\"><code>Encoder</code></a> and\n<a href=\"https://go.dev/pkg/encoding/json/jsontext#Decoder\" rel=\"nofollow ugc noopener\"><code>Decoder</code></a>\nprovide support for encoding and decoding JSON values and tokens.\nThe constructors\n<a href=\"https://go.dev/pkg/encoding/json/jsontext#Options\" rel=\"nofollow ugc noopener\">accept variadic options</a>\nthat affect the particular behavior of encoding and decoding.\nUnlike the <code>Encoder</code> and <code>Decoder</code> types declared in <code>v1</code>,\nthe new types in <code>jsontext</code> avoid muddling the distinction between syntax and\nsemantics and operate in a truly streaming manner.</p>\n<p>A JSON value is a complete unit of data and is represented in Go as\n<a href=\"https://go.dev/pkg/encoding/json/jsontext#Value\" rel=\"nofollow ugc noopener\">a named <code>[]byte</code></a>.\nIt is identical to <a href=\"https://go.dev/pkg/encoding/json#RawMessage\" rel=\"nofollow ugc noopener\"><code>RawMessage</code></a> in <code>v1</code>, which is now a type alias to <code>jsontext.Value</code>.\nA JSON value is syntactically composed of one or more JSON tokens.\nA JSON token is represented in Go as the <a href=\"https://go.dev/pkg/encoding/json/jsontext#Token\" rel=\"nofollow ugc noopener\">opaque <code>Token</code> type</a>\nwith constructors and accessor methods.\nIt is analogous to <a href=\"https://go.dev/pkg/encoding/json#Token\" rel=\"nofollow ugc noopener\"><code>Token</code></a> in <code>v1</code>\nbut is designed represent arbitrary JSON tokens without allocation.</p>\n<p>To resolve the fundamental performance problems with\nthe <code>MarshalJSON</code> and <code>UnmarshalJSON</code> interface methods,\nwe need an efficient way of encoding and decoding JSON\nas a streaming sequence of tokens and values.\nIn <code>v2</code>, we introduce the <code>MarshalJSONTo</code> and <code>UnmarshalJSONFrom</code> interface methods\nthat operate on an <code>Encoder</code> or <code>Decoder</code>, allowing the methods’ implementations\nto process JSON in a purely streaming manner. Thus, the <code>json</code> package need not\nbe responsible for validating or formatting a JSON value returned by <code>MarshalJSON</code>,\nnor would it need to be responsible for determining the boundaries of a JSON value\nprovided to <code>UnmarshalJSON</code>. These responsibilities belong to the <code>Encoder</code> and <code>Decoder</code>.</p>\n<h2 id=\"introducing-encoding-json-v2\">Introducing <code>encoding/json/v2</code></h2>\n<p>Building on the <code>jsontext</code> package, we now introduce the\n<a href=\"https://go.dev/pkg/encoding/json/v2\" rel=\"nofollow ugc noopener\"><code>encoding/json/v2</code></a> package.\nIt is designed to fix the problems in <code>v1</code>,\nwhile remaining familiar to users of the <code>v1</code> package.\nOur goal is that usages of <code>v1</code> will operate <em>mostly</em> the same if directly migrated to <code>v2</code>.</p>\n<p>Here, we primarily cover the high-level API of <code>v2</code>.\nFor examples on how to use it, we encourage readers to\nstudy <a href=\"https://go.dev/pkg/encoding/json/v2#pkg-examples\" rel=\"nofollow ugc noopener\">the examples in the <code>v2</code> package</a>,\nthe “<a href=\"https://go.dev/doc/tutorial/json\" rel=\"nofollow ugc noopener\">Working with JSON</a>” tutorial, or\nread <a href=\"https://antonz.org/go-json-v2/\" rel=\"nofollow ugc noopener\">Anton Zhiyanov’s blog covering the topic</a>.</p>\n<p>The basic API of <code>v2</code> is the following:</p>\n<pre><code>package json\n\nfunc Marshal(in any, opts ...Options) (out []byte, err error)\nfunc MarshalWrite(out io.Writer, in any, opts ...Options) error\nfunc MarshalEncode(out *jsontext.Encoder, in any, opts ...Options) error\n\nfunc Unmarshal(in []byte, out any, opts ...Options) error\nfunc UnmarshalRead(in io.Reader, out any, opts ...Options) error\nfunc UnmarshalDecode(in *jsontext.Decoder, out any, opts ...Options) error</code></pre>\n<p>The <a href=\"https://go.dev/pkg/encoding/json/v2#Marshal\" rel=\"nofollow ugc noopener\"><code>Marshal</code></a>\nand <a href=\"https://go.dev/pkg/encoding/json/v2#Unmarshal\" rel=\"nofollow ugc noopener\"><code>Unmarshal</code></a> functions\nhave a signature similar to <code>v1</code>, but accept options to configure their behavior.\nThe <a href=\"https://go.dev/pkg/encoding/json/v2#MarshalWrite\" rel=\"nofollow ugc noopener\"><code>MarshalWrite</code></a>\nand <a href=\"https://go.dev/pkg/encoding/json/v2#UnmarshalRead\" rel=\"nofollow ugc noopener\"><code>UnmarshalRead</code></a> functions\ndirectly operate on an <code>io.Writer</code> or <code>io.Reader</code>,\navoiding the need to temporarily construct an <code>Encoder</code> or <code>Decoder</code>\njust to write or read from such types.\nThe <a href=\"https://go.dev/pkg/encoding/json/v2#MarshalEncode\" rel=\"nofollow ugc noopener\"><code>MarshalEncode</code></a>\nand <a href=\"https://go.dev/pkg/encoding/json/v2#UnmarshalDecode\" rel=\"nofollow ugc noopener\"><code>UnmarshalDecode</code></a> functions\noperate on a <code>jsontext.Encoder</code> and <code>jsontext.Decoder</code> and\nis actually the underlying implementation of the previously mentioned functions.\nUnlike <code>v1</code>, options are a first-class argument to each of the marshal and unmarshal functions,\ngreatly extending the flexibility and configurability of <code>v2</code>.\nThere are <a href=\"https://go.dev/pkg/encoding/json/v2#Options\" rel=\"nofollow ugc noopener\">several options available</a>\nin <code>v2</code> which are not covered by this article.</p>\n<h3 id=\"type-specified-customization\">Type-specified customization</h3>\n<p>Similar to <code>v1</code>, <code>v2</code> allows types to define their own JSON representation\nby satisfying particular interfaces.</p>\n<pre><code>type Marshaler interface {\n    MarshalJSON() ([]byte, error)\n}\ntype MarshalerTo interface {\n    MarshalJSONTo(*jsontext.Encoder) error\n}\n\ntype Unmarshaler interface {\n    UnmarshalJSON([]byte) error\n}\ntype UnmarshalerFrom interface {\n    UnmarshalJSONFrom(*jsontext.Decoder) error\n}</code></pre>\n<p>The <a href=\"https://go.dev/pkg/encoding/json/v2#Marshaler\" rel=\"nofollow ugc noopener\"><code>Marshaler</code></a>\nand <a href=\"https://go.dev/pkg/encoding/json/v2#Unmarshaler\" rel=\"nofollow ugc noopener\"><code>Unmarshaler</code></a> interfaces\nare identical to those in <code>v1</code>.\nThe new <a href=\"https://go.dev/pkg/encoding/json/v2#MarshalerTo\" rel=\"nofollow ugc noopener\"><code>MarshalerTo</code></a>\nand <a href=\"https://go.dev/pkg/encoding/json/v2#UnmarshalerFrom\" rel=\"nofollow ugc noopener\"><code>UnmarshalerFrom</code></a> interfaces\nallow a type to represent itself as JSON using a <code>jsontext.Encoder</code> or <code>jsontext.Decoder</code>.\nThis allows options to be forwarded down the call stack, since options\ncan be retrieved via the <code>Options</code> accessor method on the <code>Encoder</code> or <code>Decoder</code>.</p>\n<p>See <a href=\"https://go.dev/pkg/encoding/json/v2#example-package-OrderedObject\" rel=\"nofollow ugc noopener\">the <code>OrderedObject</code> example</a>\nfor how to implement a custom type that maintains the ordering of JSON object members.</p>\n<h3 id=\"caller-specified-customization\">Caller-specified customization</h3>\n<p>In <code>v2</code>, the caller of <code>Marshal</code> and <code>Unmarshal</code> can also specify\na custom JSON representation for any arbitrary type,\nwhere caller-specified functions take precedence over type-defined methods\nor the default representation for a particular type.</p>\n<pre><code>func WithMarshalers(*Marshalers) Options\n\ntype Marshalers struct { ... }\nfunc MarshalFunc[T any](fn func(T) ([]byte, error)) *Marshalers\nfunc MarshalToFunc[T any](fn func(*jsontext.Encoder, T) error) *Marshalers\n\nfunc WithUnmarshalers(*Unmarshalers) Options\n\ntype Unmarshalers struct { ... }\nfunc UnmarshalFunc[T any](fn func([]byte, T) error) *Unmarshalers\nfunc UnmarshalFromFunc[T any](fn func(*jsontext.Decoder, T) error) *Unmarshalers</code></pre>\n<p><a href=\"https://go.dev/pkg/encoding/json/v2#MarshalFunc\" rel=\"nofollow ugc noopener\"><code>MarshalFunc</code></a> and\n<a href=\"https://go.dev/pkg/encoding/json/v2#MarshalToFunc\" rel=\"nofollow ugc noopener\"><code>MarshalToFunc</code></a>\nconstruct a custom marshaler that can be passed to a <code>Marshal</code> call\nusing <code>WithMarshalers</code> to override the marshaling of particular types.\nSimilarly,\n<a href=\"https://go.dev/pkg/encoding/json/v2#UnmarshalFunc\" rel=\"nofollow ugc noopener\"><code>UnmarshalFunc</code></a> and\n<a href=\"https://go.dev/pkg/encoding/json/v2#UnmarshalFromFunc\" rel=\"nofollow ugc noopener\"><code>UnmarshalFromFunc</code></a>\nsupport similar customization for <code>Unmarshal</code>.</p>\n<p><a href=\"https://go.dev/pkg/encoding/json/v2#example-package-ProtoJSON\" rel=\"nofollow ugc noopener\">The <code>ProtoJSON</code> example</a>\ndemonstrates how this feature allows serialization of all\n<a href=\"https://go.dev/pkg/google.golang.org/protobuf/proto#Message\" rel=\"nofollow ugc noopener\"><code>proto.Message</code></a> types\nto be handled by the <a href=\"https://go.dev/pkg/google.golang.org/protobuf/encoding/protojson\" rel=\"nofollow ugc noopener\"><code>protojson</code></a> package.</p>\n<h3 id=\"behavior-differences\">Behavior differences</h3>\n<p>While <code>v2</code> aims to behave <em>mostly</em> the same as <code>v1</code>,\nits behavior has changed <a href=\"https://go.dev/pkg/encoding/json#hdr-Migrating_to_v2\" rel=\"nofollow ugc noopener\">in some ways</a>\nto address problems in <code>v1</code>, most notably:</p>\n<ul><li><code>v2</code> reports an error in the presence of invalid UTF-8.</li><li><code>v2</code> reports an error if a JSON object contains a duplicate name.</li><li><code>v2</code> marshals a nil Go slice or Go map as an empty JSON array or JSON object, respectively.</li><li><p><code>v2</code> unmarshals a JSON object into a Go struct using a</p><p>case-sensitive match from the JSON member name to the Go field name.</p></li><li><p><code>v2</code> redefines the <code>omitempty</code> tag option to omit a field if it would have</p><p>encoded as an “empty” JSON value (which are <code>null</code>, <code>&quot;&quot;</code>, <code>[]</code>, and <code>{}</code>).</p></li><li><p><code>v2</code> reports an error when trying to serialize a <code>time.Duration</code>,</p><p>which currently has <a href=\"https://go.dev/issue/71631\" rel=\"nofollow ugc noopener\">no default representation</a>,\nbut provides options to let the caller decide.</p></li></ul>\n<p>For most behavior changes, there is a struct tag option or caller-specified option\nthat can configure the behavior to operate under <code>v1</code> or <code>v2</code> semantics,\nor even other caller-determined behavior.\nSee “<a href=\"https://go.dev/pkg/encoding/json#hdr-Migrating_to_v2\" rel=\"nofollow ugc noopener\">Migrating to v2</a>” for more information.</p>\n<h3 id=\"performance-optimizations\">Performance optimizations</h3>\n<p>The <code>Marshal</code> performance of <code>v2</code> is roughly at parity with <code>v1</code>.\nSometimes it is slightly faster, but other times it is slightly slower.\nThe <code>Unmarshal</code> performance of <code>v2</code> is significantly faster than <code>v1</code>,\nwith benchmarks demonstrating improvements of up to 10x.</p>\n<p>In order to obtain greater performance gains,\nexisting implementations of\n<a href=\"https://go.dev/pkg/encoding/json/v2#Marshaler\" rel=\"nofollow ugc noopener\"><code>Marshaler</code></a> and\n<a href=\"https://go.dev/pkg/encoding/json/v2#Unmarshaler\" rel=\"nofollow ugc noopener\"><code>Unmarshaler</code></a> should\nmigrate to also implement\n<a href=\"https://go.dev/pkg/encoding/json/v2#MarshalerTo\" rel=\"nofollow ugc noopener\"><code>MarshalerTo</code></a> and\n<a href=\"https://go.dev/pkg/encoding/json/v2#UnmarshalerFrom\" rel=\"nofollow ugc noopener\"><code>UnmarshalerFrom</code></a>,\nso that they can benefit from processing JSON in a purely streaming manner.\nFor example, recursive parsing of OpenAPI specifications in <code>UnmarshalJSON</code> methods\nsignificantly hurt performance in a particular service of Kubernetes\n(see <a href=\"https://github.com/kubernetes/kube-openapi/issues/315\" rel=\"nofollow ugc noopener\">kubernetes/kube-openapi#315</a>),\nwhile switching to <code>UnmarshalJSONFrom</code> improved performance by orders of magnitude.</p>\n<p>For more benchmark details, see the\n<a href=\"https://github.com/go-json-experiment/jsonbench\" rel=\"nofollow ugc noopener\"><code>go-json-experiment/jsonbench</code></a>\nrepository.</p>\n<p>On top of structural improvements, we’re continuing to invest in performance optimizations in the implementation for <a href=\"https://go.dev/issue/81315\" rel=\"nofollow ugc noopener\">cases</a> where the <code>v2</code> implementation is slower than <code>v1</code>.\nYou can expect additional improvements in Go 1.28.</p>\n<h2 id=\"compatibility\">Compatibility</h2>\n<p>The <a href=\"https://go.dev/doc/go1compat\" rel=\"nofollow ugc noopener\">Go 1 compatibility promise</a> is a core guarantee from the Go project that allows developers to build applications that will stand the test of time and continue working on future versions of Go.</p>\n<p>The original <code>encoding/json</code> and new <code>encoding/json/v2</code> packages are of course both subject to the Go 1 compatibility promise.\nApplications using <code>v1</code> will continue to be supported indefinitely and need not ever migrate to <code>v2</code>.</p>\n<p>That said, when designing the <code>v2</code> packages we wanted to do better than keeping <code>v1</code> supported.\nWe wanted to ensure that <code>v1</code> and <code>v2</code> are <em>compatible with one another</em> so that packages using different versions can work together.\nDoing so allows a smooth ecosystem migration rather than forcing users to use one version or another due to the choices of their dependencies.</p>\n<p>For instance, suppose your package uses <code>v2</code> to marshal a struct containing a field with a type defined in another package.\nThat package may use the original <code>v1</code> <a href=\"https://go.dev/pkg/encoding/json/v2#Marshaler\" rel=\"nofollow ugc noopener\"><code>MarshalJSON</code></a> method to define its marshaling behavior.\nNo problem, <code>v2</code> supports <a href=\"https://go.dev/pkg/encoding/json/v2#Marshaler\" rel=\"nofollow ugc noopener\"><code>MarshalJSON</code></a> methods, so marshaling will continue working as expected.</p>\n<p>Vice versa, suppose your package uses <code>v1</code> to marshal the same struct.\nThe other package may use the <code>v2</code> <a href=\"https://go.dev/pkg/encoding/json/v2#MarshalerTo\" rel=\"nofollow ugc noopener\"><code>MarshalJSONTo</code></a> method for better performance.\nNo problem here either, as the <code>v1</code> implementation supports <code>v2</code>’s <a href=\"https://go.dev/pkg/encoding/json/v2#MarshalerTo\" rel=\"nofollow ugc noopener\"><code>MarshalJSONTo</code></a> method under the hood.</p>\n<p>We’ve achieved this by designing the new packages such that, under the hood, <code>v1</code> is implemented in terms of <code>v2</code>.\nAs mentioned above, <code>v2</code> supports a variety of <a href=\"https://go.dev/pkg/encoding/json/v2#Options\" rel=\"nofollow ugc noopener\"><code>Options</code></a>.\nEach behavior difference is controlled by one of the these options.\nThus, <code>v1</code> can be implemented in terms of <code>v2</code> by passing the full set of <code>v1</code> compatibility options.</p>\n<p>With this approach, backwards-compatible additions such as new methods (e.g., <a href=\"https://go.dev/pkg/encoding/json/v2#MarshalerTo\" rel=\"nofollow ugc noopener\"><code>MarshalJSONTo</code></a>) or new struct tags (e.g., <a href=\"https://go.dev/pkg/encoding/json/v2#hdr-JSON_Representation_of_Go_structs\" rel=\"nofollow ugc noopener\"><code>embed</code></a>) are automatically supported to the benefit of existing <code>v1</code> users.</p>\n<h2 id=\"migration\">Migration</h2>\n<p>Implementing <code>v1</code> in terms of <code>v2</code> options has the additional benefit of allowing gradual migration of callsites.</p>\n<p><code>encoding/json</code> <a href=\"https://go.dev/pkg/encoding/json#hdr-Migrating_to_v2\" rel=\"nofollow ugc noopener\">documents</a> the full set of behavior differences between <code>v1</code> and <code>v2</code>, and which option controls that behaviors.</p>\n<p>Many applications can migrate directly to <code>v2</code> with no visible behavior changes, but applications that depend on <code>v1</code> behavior can use the options to change only the behaviors they depend on.</p>\n<p>For example, we can select all <code>v2</code> behavior except for allowing duplicate names:</p>\n<pre><code>json.Marshal(..., json.DefaultOptionsV2(), jsontext.AllowDuplicateName(true))</code></pre>\n<p>Alternatively, we can select all <code>v1</code> behavior except for disallowing duplicate names:</p>\n<pre><code>json.Marshal(..., jsonv1.DefaultOptionsV1(), jsontext.AllowDuplicateName(false))</code></pre>\n<p>The <a href=\"https://go.dev/doc/jsonv2-migration\" rel=\"nofollow ugc noopener\"><code>encoding/json/v2</code> Migration Guide</a> goes into more detail, covering a variety of scenarios for approaching migration of an application from <code>v1</code> to <code>v2</code>.</p>\n<h2 id=\"more-information\">More information</h2>\n<p>For additional references on working with the new JSON packages, see:</p>\n<ul><li>The “<a href=\"https://go.dev/doc/tutorial/json\" rel=\"nofollow ugc noopener\">Working with JSON</a>” tutorial,</li><li>The <a href=\"https://go.dev/pkg/encoding/json/v2\" rel=\"nofollow ugc noopener\"><code>encoding/json/v2</code></a> and <a href=\"https://go.dev/pkg/encoding/json/jsontext\" rel=\"nofollow ugc noopener\"><code>encoding/json/jsontext</code></a> package documentation,</li><li>The <a href=\"https://go.dev/pkg/encoding/json#hdr-Migrating_to_v2\" rel=\"nofollow ugc noopener\"><code>encoding/json</code></a> package’s <code>v2</code> comparison documentation,</li><li>and the <a href=\"https://go.dev/doc/jsonv2-migration\" rel=\"nofollow ugc noopener\"><code>encoding/json/v2</code> Migration Guide</a>.</li></ul>\n<h2 id=\"a-long-time-coming\">A long time coming</h2>\n<p>The planning for a new major version of <code>encoding/json</code> spanned years.\nIn late 2020, spurred on by the inability to fix issues in the current package,\nDaniel Martí (one of the maintainers of <code>encoding/json</code>) first drafted his\nthoughts on <a href=\"https://docs.google.com/document/d/1WQGoM44HLinH4NGBEv5drGlw5_RNW-GP7DdGEpm7Y3o\" rel=\"nofollow ugc noopener\">what a hypothetical <code>v2</code> package should look like</a>.\nSeparately, after previous work on the <a href=\"https://go.dev/blog/protobuf-apiv2\" rel=\"nofollow ugc noopener\">Go API for Protocol Buffers</a>,\nJoe Tsai was disappointed that <a href=\"https://go.dev/pkg/google.golang.org/protobuf/encoding/protojson\" rel=\"nofollow ugc noopener\">the <code>protojson</code> package</a>\nneeded to use a custom JSON implementation because <code>encoding/json</code> was\nneither capable of adhering to the stricter JSON standard that the\nProtocol Buffer specification required,\nnor of efficiently serializing JSON in a streaming manner.</p>\n<p>Believing a brighter future for JSON was both beneficial and achievable,\nDaniel and Joe joined forces to brainstorm on <code>v2</code> and\n<a href=\"https://github.com/go-json-experiment/json\" rel=\"nofollow ugc noopener\">started to build a prototype</a>\n(with the initial code being a polished version of the JSON serialization logic from the Go protobuf module).\nOver time, a few others (Roger Peppe, Chris Hines, Johan Brandhorst-Satzkorn, Damien Neil, Austin Clements, and Michael Pratt)\njoined the effort by providing design review, code review, and regression testing.\nMany of the early discussions are publicly available in our\n<a href=\"https://www.youtube.com/playlist?list=PLZgrQPcV8W8EChkaAvv-3NUu6PYmnGG3b\" rel=\"nofollow ugc noopener\">recorded meetings</a> and\n<a href=\"https://docs.google.com/document/d/1rovrOTd-wTawGMPPlPuKhwXaYBg9VszTXR9AQQL5LfI\" rel=\"nofollow ugc noopener\">meeting notes</a>.\nLater discussions are available in our <a href=\"https://go.dev/issue/76406\" rel=\"nofollow ugc noopener\"><code>encoding/json/v2</code> working group meeting notes</a>.</p>\n<p>This work has been public since the beginning,\nand we increasingly involved the wider Go community,\nfirst with a\n<a href=\"https://www.youtube.com/watch?v=avilmOcHKHE\" rel=\"nofollow ugc noopener\">GopherCon talk</a> and\n<a href=\"https://go.dev/issue/63397\" rel=\"nofollow ugc noopener\">discussion posted in late 2023</a>,\n<a href=\"https://go.dev/issue/71497\" rel=\"nofollow ugc noopener\">formal proposal posted in early 2025</a>,\nand finally <a href=\"https://go.dev/issue/71845\" rel=\"nofollow ugc noopener\">adopting <code>encoding/json/v2</code> as a Go experiment in Go 1.25</a>\nfor wider-scale testing by all Go users.</p>\n<p>The <code>v2</code> effort took about 6 years to reach this point,\nincorporating feedback from many contributors and also gaining valuable\nempirical experience from use in production settings.</p>\n<p>It’s worth noting that it’s largely been developed and promoted by people\nnot employed by Google, demonstrating that the Go project is a collaborative endeavor\nwith a thriving global community dedicated to improving the Go ecosystem.</p>\n<p>Thank you to everyone that contributed!</p>","headings":[{"level":1,"text":"A new Go API for JSON","id":"a-new-go-api-for-json"},{"level":2,"text":"Introduction","id":"introduction"},{"level":2,"text":"Problems with encoding/json","id":"problems-with-encoding-json"},{"level":3,"text":"Behavior flaws","id":"behavior-flaws"},{"level":3,"text":"API deficiencies","id":"api-deficiencies"},{"level":3,"text":"Performance limitations","id":"performance-limitations"},{"level":2,"text":"Trying to fix encoding/json directly","id":"trying-to-fix-encoding-json-directly"},{"level":2,"text":"Building on encoding/json/jsontext","id":"building-on-encoding-json-jsontext"},{"level":2,"text":"Introducing encoding/json/v2","id":"introducing-encoding-json-v2"},{"level":3,"text":"Type-specified customization","id":"type-specified-customization"},{"level":3,"text":"Caller-specified customization","id":"caller-specified-customization"},{"level":3,"text":"Behavior differences","id":"behavior-differences"},{"level":3,"text":"Performance optimizations","id":"performance-optimizations"},{"level":2,"text":"Compatibility","id":"compatibility"},{"level":2,"text":"Migration","id":"migration"},{"level":2,"text":"More information","id":"more-information"},{"level":2,"text":"A long time coming","id":"a-long-time-coming"}]}}