encoding/json/v2

suggest change

encoding/json/v2 is the second version of Go's JSON package. It fixes long-standing problems of encoding/json (now called "v1"): surprising defaults, missing configuration and slow performance.

History:

All examples in this article were run with Go 1.27. Unless noted otherwise, every API shown is new in 1.27 (or 1.25 with the experiment enabled).

This article covers:

The package has a companion, encoding/json/jsontext, which handles JSON at the syntax level: tokens, streaming encoders and decoders, raw values. It's covered in Streaming JSON with jsontext. Here we only use it for formatting options and jsontext.Value.

Marshal and Unmarshal

Import the package as encoding/json/v2. Its name is still json:

package main

import (
	"encoding/json/jsontext"
	"encoding/json/v2"
	"fmt"
	"log"
	"os"
	"strings"
)

type Book struct {
	Title   string   `json:"title"`
	Authors []string `json:"authors"`
	Year    int      `json:"year,omitzero"`
}

func main() {
	b := Book{Title: "The Go Programming Language", Authors: []string{"Donovan", "Kernighan"}, Year: 2015}

	data, err := json.Marshal(b)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(data))

	// there's no MarshalIndent: indentation is an option
	data, err = json.Marshal(b, jsontext.WithIndent("  "))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(data))

	var b2 Book
	err = json.Unmarshal([]byte(`{"title":"Go in Action","authors":["Kennedy"]}`), &b2)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%+v\n", b2)

	// streaming versions work on io.Reader / io.Writer
	var b3 Book
	r := strings.NewReader(`{"title":"Learning Go","year":2021}`)
	if err := json.UnmarshalRead(r, &b3); err != nil {
		log.Fatal(err)
	}
	if err := json.MarshalWrite(os.Stdout, b3); err != nil {
		log.Fatal(err)
	}
	fmt.Println()
}
{"title":"The Go Programming Language","authors":["Donovan","Kernighan"],"year":2015}
{
  "title": "The Go Programming Language",
  "authors": [
    "Donovan",
    "Kernighan"
  ],
  "year": 2015
}
{Title:Go in Action Authors:[Kennedy] Year:0}
{"title":"Learning Go","authors":[],"year":2021}

The signatures are the same as in v1, plus a variadic list of options:

func Marshal(in any, opts ...Options) (out []byte, err error)
func Unmarshal(in []byte, out any, opts ...Options) (err error)
func MarshalWrite(out io.Writer, in any, opts ...Options) (err error)
func UnmarshalRead(in io.Reader, out any, opts ...Options) (err error)

MarshalWrite and UnmarshalRead replace the common v1 idiom of json.NewEncoder(w).Encode(v) and json.NewDecoder(r).Decode(&v). Unlike Encoder.Encode, MarshalWrite doesn't append a newline. UnmarshalRead reads the whole input until io.EOF and fails if there is anything other than whitespace after the JSON value (e.g. jsontext: invalid character '{' after top-level value). To decode a sequence of values, use a jsontext.Decoder with UnmarshalDecode.

Notice the last line: Authors was never set, so it's a nil slice, and v2 encodes it as [] instead of null.

How v2 defaults differ from v1

The struct tags you already use (json:"name,omitempty", json:"-", omitzero) mean the same thing in v2 (with one exception for omitempty, see below). The defaults, however, are different. They are more secure and closer to what other JSON implementations do:

package main

import (
	jsonv1 "encoding/json"
	"encoding/json/v2"
	"fmt"
	"time"
)

type User struct {
	Name  string            `json:"name"`
	Admin bool              `json:"admin"`
	Tags  []string          `json:"tags"`
	Meta  map[string]string `json:"meta"`
}

func main() {
	// nil slices and maps, HTML escaping
	u := User{Name: "<ann>"}
	d1, _ := jsonv1.Marshal(u)
	d2, _ := json.Marshal(u)
	fmt.Println("v1:", string(d1))
	fmt.Println("v2:", string(d2))

	// case-insensitive matching
	in := []byte(`{"NAME":"bob","Admin":true}`)
	var u1, u2 User
	jsonv1.Unmarshal(in, &u1)
	json.Unmarshal(in, &u2)
	fmt.Printf("v1: %q admin=%v\n", u1.Name, u1.Admin)
	fmt.Printf("v2: %q admin=%v\n", u2.Name, u2.Admin)

	// duplicate names
	in = []byte(`{"name":"alice","admin":false,"admin":true}`)
	err1 := jsonv1.Unmarshal(in, &u1)
	err2 := json.Unmarshal(in, &u2)
	fmt.Println("v1:", err1, u1.Admin)
	fmt.Println("v2:", err2)

	// invalid UTF-8
	in = []byte("{\"name\":\"caf\xe9\"}")
	err1 = jsonv1.Unmarshal(in, &u1)
	err2 = json.Unmarshal(in, &u2)
	fmt.Printf("v1: %v %q\n", err1, u1.Name)
	fmt.Println("v2:", err2)

	// time.Duration
	type Job struct {
		Timeout time.Duration
	}
	d1, err1 = jsonv1.Marshal(Job{5 * time.Second})
	_, err2 = json.Marshal(Job{5 * time.Second})
	fmt.Println("v1:", string(d1), err1)
	fmt.Println("v2:", err2)
}
v1: {"name":"\u003cann\u003e","admin":false,"tags":null,"meta":null}
v2: {"name":"<ann>","admin":false,"tags":[],"meta":{}}
v1: "bob" admin=true
v2: "" admin=false
v1: <nil> true
v2: jsontext: duplicate object member name "admin"
v1: <nil> "caf�"
v2: jsontext: invalid UTF-8 within "/name" after offset 12
v1: {"Timeout":5000000000} <nil>
v2: json: cannot marshal from Go time.Duration within "/Timeout": no default representation

The most important differences:

v1 v2
nil slice / nil map null [] / {}
matching JSON names to fields case-insensitive case-sensitive
duplicate names in an object last one wins error
invalid UTF-8 silently replaced with U+FFFD error
<, >, & in strings escaped written as is
map key order sorted unspecified
time.Duration number of nanoseconds error, no default representation
[N]byte array of numbers base64 string
unmarshal array of wrong length into [N]T ignored error
omitempty omits Go zero-ish values: false, 0, nil, empty omits values that encode as JSON null, "", {}, []
bad struct tags ignored error

The case-sensitive matching and the duplicate name check close real security holes: two services parsing the same JSON shouldn't see different values. In v1, {"admin":false,"Admin":true} is accepted and the last value wins.

The omitempty change matters if you used it on a bool or number. In v2 false and 0 are not empty JSON values, so they are no longer omitted. Use omitzero (available since Go 1.24 in v1 too) for that. See Zero values and absence for the details of omitzero.

v2 also rejects malformed tags that v1 silently ignored:

type Bad struct {
	Name string `json:"name,omitEmpty"`
}

_, err := json.Marshal(Bad{})
fmt.Println(err)
json: unable to marshal from Go main.Bad: Go struct field Name has invalid appearance of `omitEmpty` tag option; specify `omitempty` instead

Options

Every v2 function takes ...json.Options. Options for marshaling and unmarshaling are in encoding/json/v2, options for syntax (indentation, escaping, UTF-8, duplicates) are in encoding/json/jsontext. You can pass both kinds to any function. Options that don't apply (e.g. an unmarshal option passed to Marshal) are ignored.

package main

import (
	"encoding/json/v2"
	"errors"
	"fmt"
)

type Config struct {
	Host  string   `json:"host"`
	Port  int      `json:"port"`
	Peers []string `json:"peers"`
}

func main() {
	// Deterministic: map keys sorted
	m := map[string]int{"zeta": 1, "alpha": 2, "mid": 3}
	d, _ := json.Marshal(m, json.Deterministic(true))
	fmt.Println(string(d))

	// RejectUnknownMembers
	in := []byte(`{"host":"localhost","port":8080,"prot":"tcp"}`)
	var c Config
	err := json.Unmarshal(in, &c, json.RejectUnknownMembers(true))
	fmt.Println(err)
	fmt.Println(errors.Is(err, json.ErrUnknownName))

	// StringifyNumbers
	d, _ = json.Marshal(Config{Host: "db", Port: 5432}, json.StringifyNumbers(true))
	fmt.Println(string(d))

	// FormatNilSliceAsNull
	d, _ = json.Marshal(Config{Host: "db"}, json.FormatNilSliceAsNull(true))
	fmt.Println(string(d))

	// MatchCaseInsensitiveNames
	in = []byte(`{"HOST":"example.com","Port":443}`)
	c = Config{}
	json.Unmarshal(in, &c, json.MatchCaseInsensitiveNames(true))
	fmt.Printf("%+v\n", c)

	// combine options once, reuse
	strict := json.JoinOptions(
		json.RejectUnknownMembers(true),
		json.Deterministic(true),
	)
	err = json.Unmarshal([]byte(`{"host":"x","extra":1}`), &c, strict)
	fmt.Println(err)

	v, ok := json.GetOption(strict, json.RejectUnknownMembers)
	fmt.Println(v, ok)
}
{"alpha":2,"mid":3,"zeta":1}
json: cannot unmarshal JSON string into Go main.Config: unknown object member name "prot"
true
{"host":"db","port":"5432","peers":[]}
{"host":"db","port":0,"peers":null}
{Host:example.com Port:443 Peers:[]}
json: cannot unmarshal JSON string into Go main.Config: unknown object member name "extra"
true true

The most useful options:

json.JoinOptions combines several options into one value you can store in a variable. When the same option is given more than once, the later one wins. json.GetOption reads an option back.

Options configure a single call. There is no global state to change, so different parts of a program (or different libraries) can use different settings without stepping on each other.

New struct tag options

case: per-field name matching

The case:ignore tag option makes matching for one field case-insensitive (and ignore - and _), regardless of the options passed. case:strict forces case-sensitive matching, even with MatchCaseInsensitiveNames(true):

package main

import (
	"encoding/json/v2"
	"fmt"
)

type Request struct {
	UserID string `json:"user_id,case:ignore"`
	Action string `json:"action"`
}

func main() {
	inputs := []string{
		`{"user_id":"u1","action":"read"}`,
		`{"UserID":"u2","Action":"write"}`,
		`{"USER-ID":"u3","ACTION":"delete"}`,
	}
	for _, s := range inputs {
		var r Request
		json.Unmarshal([]byte(s), &r)
		fmt.Printf("%-35s -> %q %q\n", s, r.UserID, r.Action)
	}
}
{"user_id":"u1","action":"read"}    -> "u1" "read"
{"UserID":"u2","Action":"write"}    -> "u2" ""
{"USER-ID":"u3","ACTION":"delete"}  -> "u3" ""

embed: inlining and capturing unknown members

In v1 the only way to flatten a struct's fields into the parent JSON object is Go struct embedding. v2 adds the embed tag option, which works on a named field too.

When the field type is jsontext.Value or map[string]T, it becomes a fallback: it collects all object members that don't match any other field. When marshaling, they are written back:

package main

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

type Audit struct {
	CreatedBy string `json:"created_by"`
	CreatedAt string `json:"created_at"`
}

type Doc struct {
	ID    int            `json:"id"`
	Audit Audit          `json:",embed"`
	Extra jsontext.Value `json:",embed"`
}

type Settings struct {
	Theme string         `json:"theme"`
	Rest  map[string]any `json:",embed"`
}

func main() {
	in := `{"id":7,"created_by":"ann","created_at":"2026-01-02","color":"red","size":3}`
	var d Doc
	if err := json.Unmarshal([]byte(in), &d); err != nil {
		panic(err)
	}
	fmt.Printf("id=%d by=%s extra=%s\n", d.ID, d.Audit.CreatedBy, d.Extra)
	out, _ := json.Marshal(d)
	fmt.Println(string(out))

	var s Settings
	err := json.Unmarshal([]byte(`{"theme":"dark","fontSize":14,"vim":true}`), &s,
		json.RejectUnknownMembers(true))
	fmt.Println(s.Theme, s.Rest, err)
	s.Rest["vim"] = false
	out, _ = json.Marshal(s, json.Deterministic(true))
	fmt.Println(string(out))
}
id=7 by=ann extra={"color":"red","size":3}
{"id":7,"created_by":"ann","created_at":"2026-01-02","color":"red","size":3}
dark map[fontSize:14 vim:true] <nil>
{"theme":"dark","fontSize":14,"vim":false}

This lets you round-trip a document without losing fields your program doesn't know about, which is hard to do in v1. A struct can have only one fallback field. With a fallback there are no unknown members, so RejectUnknownMembers doesn't fail.

embed must be the only option in the tag: json:",embed". Embedded Go structs (struct{ Audit }) are implicitly embedded, as in v1.

format: not available yet

The v2 design includes a format: tag option (e.g. json:",format:DateOnly" for time.Time or format:hex for []byte). In Go 1.27 it's disabled and using it is an error:

type Event struct {
	At time.Time `json:"at,format:DateOnly"`
}

_, err := json.Marshal(Event{})
fmt.Println(err)
json: unable to marshal from Go main.Event: Go struct field At has unsupported `format` tag option

Until it's enabled, use a custom type with marshal methods (see Custom JSON marshaling) or a per-call marshaler, shown next.

Per-call custom marshalers

In v1 the only way to customize how a type is encoded is to give the type MarshalJSON and UnmarshalJSON methods. That's impossible for types you don't own (like time.Duration), and it applies everywhere the type is used.

v2 adds marshalers that are passed as options to a single call:

Pass them with json.WithMarshalers and json.WithUnmarshalers. Combine several with json.JoinMarshalers and json.JoinUnmarshalers.

package main

import (
	"encoding/json/jsontext"
	"encoding/json/v2"
	"errors"
	"fmt"
	"strings"
	"time"
)

type Job struct {
	Name    string        `json:"name"`
	Timeout time.Duration `json:"timeout"`
	Secret  string        `json:"secret"`
}

func main() {
	// time.Duration as "1m30s" instead of an error
	durM := json.MarshalFunc(func(d time.Duration) ([]byte, error) {
		return json.Marshal(d.String())
	})
	durU := json.UnmarshalFunc(func(b []byte, d *time.Duration) error {
		var s string
		if err := json.Unmarshal(b, &s); err != nil {
			return err
		}
		v, err := time.ParseDuration(s)
		*d = v
		return err
	})

	j := Job{Name: "backup", Timeout: 90 * time.Second, Secret: "hunter2"}
	out, err := json.Marshal(j, json.WithMarshalers(durM))
	fmt.Println(string(out), err)

	var j2 Job
	err = json.Unmarshal(out, &j2, json.WithUnmarshalers(durU))
	fmt.Println(j2.Timeout, err)

	// MarshalToFunc writes tokens directly to the encoder.
	// Returning errors.ErrUnsupported falls back to the default encoding.
	redact := json.MarshalToFunc(func(enc *jsontext.Encoder, s string) error {
		if enc.StackPointer().LastToken() == "secret" {
			return enc.WriteToken(jsontext.String("***"))
		}
		return errors.ErrUnsupported
	})
	all := json.JoinMarshalers(durM, redact)
	out, err = json.Marshal(j, json.WithMarshalers(all))
	fmt.Println(string(out), err)

	// UnmarshalFromFunc reads from the decoder: trim and lowercase all strings
	lower := json.UnmarshalFromFunc(func(dec *jsontext.Decoder, s *string) error {
		tok, err := dec.ReadToken()
		if err != nil {
			return err
		}
		if tok.Kind() != '"' {
			return errors.New("expected a string")
		}
		*s = strings.ToLower(strings.TrimSpace(tok.String()))
		return nil
	})
	var tags []string
	err = json.Unmarshal([]byte(`[" Go ", "JSON", "V2"]`), &tags, json.WithUnmarshalers(lower))
	fmt.Printf("%q %v\n", tags, err)
}
{"name":"backup","timeout":"1m30s","secret":"hunter2"} <nil>
1m30s <nil>
{"name":"backup","timeout":"1m30s","secret":"***"} <nil>
["go" "json" "v2"] <nil>

Things to note:

Types can still implement MarshalJSON and UnmarshalJSON; v2 calls them. v2 also adds the MarshalerTo and UnmarshalerFrom interfaces (methods MarshalJSONTo and UnmarshalJSONFrom) that work with jsontext.Encoder and jsontext.Decoder directly; they are described in Streaming JSON with jsontext.

Errors with location

v2 reports where in the input an error happened, as a byte offset and as a JSON Pointer path:

package main

import (
	"encoding/json/jsontext"
	"encoding/json/v2"
	"errors"
	"fmt"
)

type Item struct {
	SKU   string `json:"sku"`
	Count int    `json:"count"`
}

type Order struct {
	ID    int    `json:"id"`
	Items []Item `json:"items"`
}

func main() {
	in := `{"id":1,"items":[{"sku":"a","count":2},{"sku":"b","count":"three"}]}`
	var o Order
	err := json.Unmarshal([]byte(in), &o)
	fmt.Println(err)

	var serr *json.SemanticError
	if errors.As(err, &serr) {
		fmt.Println("pointer:", serr.JSONPointer)
		fmt.Println("offset: ", serr.ByteOffset)
		fmt.Println("kind:   ", serr.JSONKind)
		fmt.Println("go type:", serr.GoType)
	}

	in = `{"id":1,"items":[{"sku":"a",}]}`
	err = json.Unmarshal([]byte(in), &o)
	fmt.Println(err)
	var synerr *jsontext.SyntacticError
	if errors.As(err, &synerr) {
		fmt.Println("pointer:", synerr.JSONPointer, "offset:", synerr.ByteOffset)
	}
}
json: cannot unmarshal JSON string into Go int within "/items/1/count"
pointer: /items/1/count
offset:  58
kind:    string
go type: int
jsontext: invalid character ',' at start of value within "/items/0" after offset 27
pointer: /items/0 offset: 27

There are 2 kinds of errors:

For comparison, v1 reports the first error as json: cannot unmarshal string into Go struct field Order.items.1.count of type int and the location is only available as text. In v2 the path is a structured jsontext.Pointer field, in standard JSON Pointer syntax, and syntax errors carry it too.

json.ErrUnknownName is the underlying error for unknown members, so you can check for it with errors.Is, as shown in the options example.

encoding/json is now implemented with v2

Since Go 1.27, encoding/json (v1) is a thin layer over v2. jsonv1.Marshal(v) is literally jsonv2.Marshal(v, jsonv1.DefaultOptionsV1()). The v1 behavior is described by a set of options, most of them new in encoding/json in Go 1.27:

plus v2 and jsontext options like Deterministic, FormatNilSliceAsNull, MatchCaseInsensitiveNames, AllowDuplicateNames, AllowInvalidUTF8 and EscapeForHTML. DefaultOptionsV1() sets all of them.

Because options are applied in order and later ones win, you can mix the two behaviors:

package main

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

type Task struct {
	Title   string        `json:"title"`
	Done    bool          `json:"done,omitempty"`
	Labels  []string      `json:"labels"`
	Timeout time.Duration `json:"timeout"`
}

func main() {
	t := Task{Title: "write docs", Timeout: time.Minute}

	a, _ := jsonv1.Marshal(t)
	fmt.Println("v1:            ", string(a))

	// exactly v1 behavior, via v2
	b, _ := json.Marshal(t, jsonv1.DefaultOptionsV1())
	fmt.Println("v2+V1 options: ", string(b))

	// mostly v1, but nil slices become []
	c, _ := json.Marshal(t, jsonv1.DefaultOptionsV1(), json.FormatNilSliceAsNull(false))
	fmt.Println("v1 minus nulls:", string(c))

	// mostly v2, but keep v1's Duration-as-nanoseconds
	d, err := json.Marshal(t, jsonv1.FormatDurationAsNano(true))
	fmt.Println("v2 plus nanos: ", string(d), err)

	// v1 accepts duplicates; reject them while staying otherwise v1
	var t2 Task
	in := []byte(`{"title":"a","title":"b"}`)
	err = json.Unmarshal(in, &t2, jsonv1.DefaultOptionsV1(), jsontext.AllowDuplicateNames(false))
	fmt.Println(err)
}
v1:             {"title":"write docs","labels":null,"timeout":60000000000}
v2+V1 options:  {"title":"write docs","labels":null,"timeout":60000000000}
v1 minus nulls: {"title":"write docs","labels":[],"timeout":60000000000}
v2 plus nanos:  {"title":"write docs","done":false,"labels":[],"timeout":60000000000} <nil>
duplicate object member name

Notice "done":false in the v2 output: v2's omitempty doesn't omit false. Changing the tag to omitzero gives the same output in v1 and v2. The last error is short because DefaultOptionsV1 includes ReportErrorsWithLegacySemantics, which keeps v1-style error messages.

json.DefaultOptionsV2() does the reverse: it resets everything before it to v2 defaults.

Some v1 types are now aliases of v2 types: jsonv1.Marshaler and jsonv1.Unmarshaler are the same interfaces as in v2, and jsonv1.RawMessage is an alias for jsontext.Value. Existing MarshalJSON methods work with both versions.

Re-implementing v1 was done carefully to keep its behavior, but error message text changed in some places. If you depend on exact error strings, or you hit a regression, you can build with the old implementation:

$ GOEXPERIMENT=nojsonv2 go build

With nojsonv2, encoding/json uses the old code and encoding/json/v2 and encoding/json/jsontext aren't available: importing them fails with build constraints exclude all Go files.

Migrating from v1

You don't have to migrate: the v1 package will remain supported. For new code, the encoding/json documentation recommends v2.

A safe way to move existing code:

  1. Change the import to encoding/json/v2 and pass jsonv1.DefaultOptionsV1() to every call. Output is identical to v1.
  2. Fix your types so they don't depend on v1 quirks: replace omitempty on bool, number, pointer and interface fields with omitzero, add case:ignore to fields that need loose matching, and give time.Duration fields an explicit representation.
  3. Remove DefaultOptionsV1() and opt back into specific v1 behaviors only where needed, e.g. json.FormatNilSliceAsNull(true) if a JavaScript client expects null.
  4. Replace json.NewDecoder(r).Decode(&v) with json.UnmarshalRead(r, &v), MarshalIndent with jsontext.WithIndent, and Decoder.DisallowUnknownFields with json.RejectUnknownMembers(true).

Watch out for:

See also:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents