Streaming JSON with jsontext

suggest change

encoding/json/jsontext is the low-level half of Go's new JSON implementation. encoding/json/v2 does semantic work: it maps JSON to Go values (marshal / unmarshal). jsontext does syntactic work: it reads and writes JSON tokens and raw values, without knowing anything about Go types. Both packages appeared in Go 1.25 behind GOEXPERIMENT=jsonv2, and are available by default since Go 1.27. All examples were run with Go 1.27.

You need jsontext when:

This article covers:

In v1 you have json.Decoder.Token, which also streams tokens, but it returns every token as an any (which allocates for strings and numbers), doesn't track where you are in the document and has no matching encoder. The Pull (streaming) XML parsing article shows the same pull approach for XML.

Tokens and values

A JSON token is one of: null, true, false, a string, a number, {, }, [ or ]. Commas and colons are implied by the grammar, so they aren't tokens. A JSON value is a complete unit: a literal, a string, a number, or a whole object or array. jsontext.Token represents a token, jsontext.Value (a []byte) represents a value as raw text.

Decoder.ReadToken returns the next token. Token.Kind() tells you what it is, Token.String() returns the unescaped string for a JSON string and the raw text for anything else:

package main

import (
	"fmt"
	"io"
	"log"
	"strings"

	"encoding/json/jsontext"
)

const doc = `{
  "name": "Ann",
  "age": 34,
  "admin": false,
  "tags": ["go", "sql"],
  "manager": null
}`

func main() {
	dec := jsontext.NewDecoder(strings.NewReader(doc))
	for {
		tok, err := dec.ReadToken()
		if err == io.EOF {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%-7v %-8s depth=%d ptr=%q\n",
			tok.Kind(), tok, dec.StackDepth(), dec.StackPointer())
	}
}
{       {        depth=1 ptr=""
string  name     depth=1 ptr="/name"
string  Ann      depth=1 ptr="/name"
string  age      depth=1 ptr="/age"
number  34       depth=1 ptr="/age"
string  admin    depth=1 ptr="/admin"
false   false    depth=1 ptr="/admin"
string  tags     depth=1 ptr="/tags"
[       [        depth=2 ptr="/tags"
string  go       depth=2 ptr="/tags/0"
string  sql      depth=2 ptr="/tags/1"
]       ]        depth=1 ptr="/tags"
string  manager  depth=1 ptr="/manager"
null    null     depth=1 ptr="/manager"
}       }        depth=0 ptr=""

The Kind values are bytes that look like the token: '{', '}', '[', ']', '"' for strings, '0' for numbers, 'n', 't', 'f' for literals. You can compare them with constants like jsontext.KindBeginObject or simply with '{'.

The decoder keeps track of the nesting:

To read numbers use Token.Int(), Token.Uint() or Token.Float(). They return an error if the number doesn't fit (e.g. 1.5 as an int64) and panic if the token isn't a number, so check Kind() first.

Two more methods make navigation easy:

Processing a huge array one element at a time

The most common reason for streaming: a file like {"generated": "...", "orders": [ ...millions of objects... ]}. Unmarshaling it requires memory for all orders. With jsontext we walk down to the array token by token and then unmarshal one element at a time with json.UnmarshalDecode, which reads exactly one value from the decoder:

package main

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"runtime"

	"encoding/json/jsontext"
	"encoding/json/v2"
)

type Order struct {
	ID       int     `json:"id"`
	Customer string  `json:"customer"`
	Total    float64 `json:"total"`
}

// writeOrders simulates a huge file: {"generated":"...","orders":[...]}
func writeOrders(w io.Writer, n int) {
	bw := bufio.NewWriter(w)
	fmt.Fprint(bw, `{"generated":"2026-10-17","orders":[`)
	for i := range n {
		if i > 0 {
			bw.WriteByte(',')
		}
		fmt.Fprintf(bw, `{"id":%d,"customer":"c%d","total":%d.50}`, i, i%100, i%10)
	}
	fmt.Fprint(bw, `]}`)
	bw.Flush()
}

func processOrders(r io.Reader, fn func(Order)) error {
	dec := jsontext.NewDecoder(r)
	if tok, err := dec.ReadToken(); err != nil || tok.Kind() != '{' {
		return fmt.Errorf("expected object: %v", err)
	}
	for dec.PeekKind() == '"' {
		name, err := dec.ReadToken()
		if err != nil {
			return err
		}
		if name.String() != "orders" {
			// not interested: skip the whole value, however big
			if err := dec.SkipValue(); err != nil {
				return err
			}
			continue
		}
		if _, err := dec.ReadToken(); err != nil { // [
			return err
		}
		for dec.PeekKind() != ']' {
			var o Order
			if err := json.UnmarshalDecode(dec, &o); err != nil {
				return err
			}
			fn(o)
		}
		if _, err := dec.ReadToken(); err != nil { // ]
			return err
		}
	}
	_, err := dec.ReadToken() // }
	return err
}

func main() {
	const n = 1_000_000
	pr, pw := io.Pipe()
	go func() {
		writeOrders(pw, n)
		pw.Close()
	}()

	var count int
	var sum float64
	err := processOrders(pr, func(o Order) {
		count++
		sum += o.Total
	})
	if err != nil {
		log.Fatal(err)
	}
	var ms runtime.MemStats
	runtime.ReadMemStats(&ms)
	fmt.Printf("orders: %d, sum: %.2f\n", count, sum)
	fmt.Printf("heap in use: %d KB\n", ms.HeapInuse/1024)
}
orders: 1000000, sum: 5000000.00
heap in use: 3912 KB

The generated input is about 44 MB, but the heap stays at a few MB (the exact number varies from run to run). Only one Order exists at a time, and the decoder only buffers as much input as it needs.

The pattern for a container is always the same:

  1. ReadToken() to consume { or [
  2. loop while PeekKind() isn't } or ]; inside an object, read the name with ReadToken() and then handle or SkipValue() the value
  3. ReadToken() to consume } or ]

The decoder validates everything it reads. If the file is truncated or malformed, one of the calls returns an error, so you don't silently process half a file.

JSON Lines

A Decoder accepts any number of top-level values in a row, which is what JSON Lines (NDJSON) logs look like. Call UnmarshalDecode in a loop until it returns io.EOF:

package main

import (
	"fmt"
	"io"
	"log"
	"strings"

	"encoding/json/jsontext"
	"encoding/json/v2"
)

type LogLine struct {
	Level string `json:"level"`
	Msg   string `json:"msg"`
}

const input = `{"level":"info","msg":"started"}
{"level":"warn","msg":"disk 91% full"}
{"level":"error","msg":"write failed"}
`

func main() {
	dec := jsontext.NewDecoder(strings.NewReader(input))
	for {
		var l LogLine
		err := json.UnmarshalDecode(dec, &l)
		if err == io.EOF {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%-5s %s (ends at byte %d)\n", l.Level, l.Msg, dec.InputOffset())
	}
}
info  started (ends at byte 32)
warn  disk 91% full (ends at byte 71)
error write failed (ends at byte 110)

Extracting a value by JSON pointer

Sometimes you need one value from a big document, e.g. a single setting from a large config, or one field of a big API response. Pointer.Tokens() iterates over the segments of a JSON pointer. For each segment we skip the members or elements we don't want and descend into the one we want. At the end ReadValue() returns the target as raw JSON:

package main

import (
	"fmt"
	"io"
	"strconv"
	"strings"

	"encoding/json/jsontext"
)

const doc = `{
  "app": "shop",
  "servers": [
    {"name": "web", "port": 8081},
    {"name": "db",  "port": 5432, "replicas": [{"host": "r1"}, {"host": "r2"}]}
  ]
}`

// findValue returns the value at the JSON pointer ptr (RFC 6901),
// skipping everything else without decoding it.
func findValue(r io.Reader, ptr jsontext.Pointer) (jsontext.Value, error) {
	dec := jsontext.NewDecoder(r)
	for want := range ptr.Tokens() {
		switch dec.PeekKind() {
		case '{':
			dec.ReadToken()
			for {
				if dec.PeekKind() == '}' {
					return nil, fmt.Errorf("%s: no member %q", dec.StackPointer(), want)
				}
				name, err := dec.ReadToken()
				if err != nil {
					return nil, err
				}
				if name.String() == want {
					break
				}
				if err := dec.SkipValue(); err != nil {
					return nil, err
				}
			}
		case '[':
			dec.ReadToken()
			idx, err := strconv.Atoi(want)
			if err != nil {
				return nil, fmt.Errorf("bad array index %q", want)
			}
			for range idx {
				if dec.PeekKind() == ']' {
					return nil, fmt.Errorf("index %d out of range", idx)
				}
				if err := dec.SkipValue(); err != nil {
					return nil, err
				}
			}
		default:
			return nil, fmt.Errorf("can't descend into %v", dec.PeekKind())
		}
	}
	v, err := dec.ReadValue()
	return v.Clone(), err // v is only valid until the next read
}

func main() {
	for _, p := range []jsontext.Pointer{
		"/servers/1/replicas/0/host",
		"/servers/0",
		"/servers/1/port",
		"/servers/5",
		"/app/x",
	} {
		v, err := findValue(strings.NewReader(doc), p)
		if err != nil {
			fmt.Printf("%-28s error: %v\n", p, err)
			continue
		}
		fmt.Printf("%-28s %s (%v)\n", p, v, v.Kind())
	}
}
/servers/1/replicas/0/host   "r1" (string)
/servers/0                   {"name": "web", "port": 8081} ({)
/servers/1/port              5432 (number)
/servers/5                   error: index 5 out of range
/app/x                       error: can't descend into string

Notice v.Clone(). A token returned by ReadToken and a value returned by ReadValue point into the decoder's internal buffer and are only valid until the next read, peek or skip call. To keep them longer, call Clone() or convert to a Go value right away (tok.String(), tok.Int(), string(v)).

The decoder checks this for tokens. Using a stale token panics:

package main

import (
	"fmt"
	"strings"

	"encoding/json/jsontext"
)

func main() {
	dec := jsontext.NewDecoder(strings.NewReader(`["a", "b", "c"]`))
	dec.ReadToken() // [
	var kept []jsontext.Token
	var cloned []jsontext.Token
	for dec.PeekKind() != ']' {
		tok, _ := dec.ReadToken()
		kept = append(kept, tok)             // BUG: voided by the next read
		cloned = append(cloned, tok.Clone()) // OK: owns its data
	}
	fmt.Println(cloned[0].String(), cloned[1].String(), cloned[2].String())
	fmt.Println(kept[0].String())
}
a b c
panic: invalid jsontext.Token; it has been voided by a subsequent json.Decoder call

There is no such check for a Value: a stale one may silently change when the buffer is reused, so be careful with them.

jsontext.Value: raw JSON

jsontext.Value is the v2 equivalent of json.RawMessage. As a struct field it captures the raw text of a value during unmarshaling. A typical use is a message envelope where the type field decides how to decode data:

package main

import (
	"fmt"
	"log"

	"encoding/json/jsontext"
	"encoding/json/v2"
)

type Event struct {
	Type string         `json:"type"`
	Data jsontext.Value `json:"data"` // decoded later, once we know the type
}

type Click struct {
	X, Y int
}

type KeyPress struct {
	Key string
}

const input = `[
	{"type": "click", "data": {"X": 10, "Y": 20}},
	{"type": "key",   "data": {"Key": "Enter"}},
	{"type": "scroll","data": [1, 2, 3]}
]`

func main() {
	var events []Event
	if err := json.Unmarshal([]byte(input), &events); err != nil {
		log.Fatal(err)
	}
	for _, e := range events {
		switch e.Type {
		case "click":
			var c Click
			if err := json.Unmarshal(e.Data, &c); err != nil {
				log.Fatal(err)
			}
			fmt.Printf("click at %d,%d\n", c.X, c.Y)
		case "key":
			var k KeyPress
			if err := json.Unmarshal(e.Data, &k); err != nil {
				log.Fatal(err)
			}
			fmt.Printf("key %s\n", k.Key)
		default:
			fmt.Printf("unknown %q (%v): %s\n", e.Type, e.Data.Kind(), e.Data)
		}
	}

	// Marshal writes a Value verbatim (after validating it)
	out, _ := json.Marshal(Event{Type: "raw", Data: jsontext.Value(`{"ok":true}`)})
	fmt.Println(string(out))

	_, err := json.Marshal(Event{Type: "bad", Data: jsontext.Value(`{"ok":}`)})
	fmt.Println(err)
}
click at 10,20
key Enter
unknown "scroll" ([): [1, 2, 3]
{"type":"raw","data":{"ok":true}}
json: cannot marshal from Go jsontext.Value: invalid character '}' at start of value within "/data/ok" after offset 27

Unknown data is kept exactly as it appeared in the input, including the spaces in [1, 2, 3]. When marshaling, a Value is validated and written as is, so a broken Value causes an error instead of producing broken output.

Also see Parsing arbitrary JSON documents for decoding into map[string]any, which is simpler when the documents are small.

Formatting: Compact, Indent, Canonicalize

Value has methods that reformat it in place. Since they modify the slice, they have pointer receivers:

package main

import (
	"fmt"
	"log"

	"encoding/json/jsontext"
)

func main() {
	v := jsontext.Value(`{ "name":"Ann",  "tags":["go","sql"], "age":34,"score":1.50E2 }`)
	fmt.Println("valid:", v.IsValid(), "kind:", v.Kind())

	if err := v.Compact(); err != nil {
		log.Fatal(err)
	}
	fmt.Println(v)

	if err := v.Indent(jsontext.WithIndent("  ")); err != nil {
		log.Fatal(err)
	}
	fmt.Println(v)

	// sorted names, minimal numbers, no whitespace (RFC 8785)
	if err := v.Canonicalize(); err != nil {
		log.Fatal(err)
	}
	fmt.Println(v)

	// Format takes any combination of options
	err := v.Format(jsontext.SpaceAfterColon(true), jsontext.SpaceAfterComma(true))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(v)

	// formatting is lenient, IsValid is strict
	dup := jsontext.Value(`{"a": 1, "a": 2}`)
	fmt.Println("compact:", dup.Compact(), dup)
	fmt.Println("valid:", dup.IsValid())

	// AppendFormat formats a string or []byte into a buffer
	out, err := jsontext.AppendFormat(nil, `[1,  2]`, jsontext.SpaceAfterComma(true))
	fmt.Println(string(out), err)
}
valid: true kind: {
{"name":"Ann","tags":["go","sql"],"age":34,"score":1.50E2}
{
  "name": "Ann",
  "tags": [
    "go",
    "sql"
  ],
  "age": 34,
  "score": 1.50E2
}
{"age":34,"name":"Ann","score":150,"tags":["go","sql"]}
{"age": 34, "name": "Ann", "score": 150, "tags": ["go", "sql"]}
compact: <nil> {"a":1,"a":2}
valid: false
[1, 2] <nil>

Compact and Indent are lenient: they accept duplicate names and invalid UTF-8, because their job is to change whitespace, not to judge the content. IsValid checks strictly (RFC 7493: valid UTF-8 and unique names). jsontext.AppendFormat does the same as Format but takes a string or []byte and appends to a buffer.

This is a convenient way to pretty-print JSON you received, e.g. a response body in a debugging tool, without decoding it into Go values.

Writing JSON with Encoder

jsontext.Encoder is the counterpart of the decoder. WriteToken writes one token, WriteValue writes a complete raw value, and json.MarshalEncode marshals a Go value into the stream. You can mix all three. The constructors for tokens are jsontext.String, Int, Uint, Float, Bool and the variables BeginObject, EndObject, BeginArray, EndArray, Null, True, False:

package main

import (
	"log"
	"os"

	"encoding/json/jsontext"
	"encoding/json/v2"
)

type User struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
}

func main() {
	enc := jsontext.NewEncoder(os.Stdout, jsontext.Multiline(true), jsontext.WithIndent("  "))

	must := func(err error) {
		if err != nil {
			log.Fatal(err)
		}
	}
	must(enc.WriteToken(jsontext.BeginObject))
	must(enc.WriteToken(jsontext.String("count")))
	must(enc.WriteToken(jsontext.Int(3)))
	must(enc.WriteToken(jsontext.String("users")))
	must(enc.WriteToken(jsontext.BeginArray))
	for i, name := range []string{"Ann", "Bob", "Cid"} {
		// mix tokens with marshaled Go values
		must(json.MarshalEncode(enc, User{ID: i + 1, Name: name}))
	}
	must(enc.WriteToken(jsontext.EndArray))
	must(enc.WriteToken(jsontext.String("raw")))
	must(enc.WriteValue(jsontext.Value(`{"pre": "formatted"}`)))
	must(enc.WriteToken(jsontext.EndObject))
}
{
  "count": 3,
  "users": [
    {
      "id": 1,
      "name": "Ann"
    },
    {
      "id": 2,
      "name": "Bob"
    },
    {
      "id": 3,
      "name": "Cid"
    }
  ],
  "raw": {
    "pre": "formatted"
  }
}

With Multiline(true) the encoder indents everything, including values passed to WriteValue. Without options it writes compact JSON.

This is how you produce a large JSON response without building it in memory first: write the opening tokens, then marshal rows one at a time as you read them from a database, then write the closing tokens. The encoder writes to the io.Writer whenever its buffer fills up and after each complete top-level value.

The encoder enforces the JSON grammar, the same way the decoder does. After each top-level value it writes a newline, so writing several values produces JSON Lines:

package main

import (
	"fmt"
	"os"

	"encoding/json/jsontext"
)

func main() {
	enc := jsontext.NewEncoder(os.Stdout)
	for i := range 3 {
		enc.WriteToken(jsontext.BeginObject)
		enc.WriteToken(jsontext.String("n"))
		enc.WriteToken(jsontext.Int(int64(i)))
		enc.WriteToken(jsontext.EndObject)
	}

	// the encoder enforces the JSON grammar
	enc.WriteToken(jsontext.BeginObject)
	err := enc.WriteToken(jsontext.Int(1)) // object names must be strings
	fmt.Println(err)
	err = enc.WriteToken(jsontext.EndArray)
	fmt.Println(err)
}
{"n":0}
{"n":1}
{"n":2}
jsontext: object member name must be a string after offset 25
jsontext: mismatching structural token for object or array after offset 25

A rejected token returns a *jsontext.SyntacticError and leaves the encoder state unchanged.

Transforming a stream: redacting secrets

A decoder and an encoder together form a pipeline that can transform JSON of any size and shape without knowing its schema. This one replaces the value of every password or token member, at any depth, with "***":

package main

import (
	"io"
	"log"
	"os"
	"strings"

	"encoding/json/jsontext"
)

const input = `{"user": "ann", "password": "hunter2",
  "sessions": [{"id": 1, "token": {"value": "abc", "exp": 99}}, {"id": 2, "token": "xyz"}],
  "note": "password"}`

var secret = map[string]bool{"password": true, "token": true}

// redact copies JSON from r to w token by token, replacing the value
// of any member named in secret, at any depth, with "***".
func redact(w io.Writer, r io.Reader) error {
	dec := jsontext.NewDecoder(r)
	enc := jsontext.NewEncoder(w)
	for {
		tok, err := dec.ReadToken()
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}
		if err := enc.WriteToken(tok); err != nil {
			return err
		}
		// An odd count inside an object means we just read a member name.
		kind, n := dec.StackIndex(dec.StackDepth())
		if kind == '{' && n%2 == 1 && secret[tok.String()] {
			if err := dec.SkipValue(); err != nil {
				return err
			}
			if err := enc.WriteToken(jsontext.String("***")); err != nil {
				return err
			}
		}
	}
}

func main() {
	if err := redact(os.Stdout, strings.NewReader(input)); err != nil {
		log.Fatal(err)
	}
}
{"user":"ann","password":"***","sessions":[{"id":1,"token":"***"},{"id":2,"token":"***"}],"note":"password"}

To tell a member name from a string value we use StackIndex: inside an object the count of tokens read is odd right after a name. SkipValue throws away the secret, whether it's a string or a whole object like the first token. The string "password" in note is a value, not a name, so it's left alone.

If your data maps to Go structs, a per-call marshaler is simpler (see "Per-call custom marshalers" in encoding/json/v2). The token pipeline is for JSON whose structure you don't know or don't want to model.

Validating and errors

Reading every token is the cheapest way to check that input is valid JSON, since nothing is stored:

package main

import (
	"errors"
	"fmt"
	"io"
	"strings"

	"encoding/json/jsontext"
)

// validate reads every token, so it checks the whole input
// without building anything in memory.
func validate(s string, opts ...jsontext.Options) error {
	dec := jsontext.NewDecoder(strings.NewReader(s), opts...)
	for {
		_, err := dec.ReadToken()
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}
	}
}

func main() {
	inputs := []string{
		`{"items": [1, 2, 3,]}`,
		`{"a": {"b": true, "b": false}}`,
		`{"name": "Ann"`,
		`{"a": 1} {"a": 2}`,
	}
	for _, s := range inputs {
		err := validate(s)
		fmt.Printf("%-32s %v\n", s, err)
		var se *jsontext.SyntacticError
		if errors.As(err, &se) {
			fmt.Printf("%32s offset=%d pointer=%q\n", "", se.ByteOffset, se.JSONPointer)
		}
		if errors.Is(err, jsontext.ErrDuplicateName) {
			fmt.Printf("%32s duplicate name\n", "")
		}
		if errors.Is(err, io.ErrUnexpectedEOF) {
			fmt.Printf("%32s truncated input\n", "")
		}
	}

	err := validate(`{"a": {"b": true, "b": false}}`, jsontext.AllowDuplicateNames(true))
	fmt.Println("with AllowDuplicateNames:", err)
}
{"items": [1, 2, 3,]}            jsontext: invalid character ',' at start of value within "/items" after offset 18
                                 offset=18 pointer="/items"
{"a": {"b": true, "b": false}}   jsontext: duplicate object member name "b" within "/a"
                                 offset=18 pointer="/a/b"
                                 duplicate name
{"name": "Ann"                   jsontext: unexpected EOF after offset 14
                                 offset=14 pointer=""
                                 truncated input
{"a": 1} {"a": 2}                <nil>
with AllowDuplicateNames: <nil>

Other decoder options include AllowInvalidUTF8. Encoder options include EscapeForHTML, EscapeForJS, SpaceAfterColon and SpaceAfterComma.

MarshalerTo and UnmarshalerFrom

The v1 interfaces json.Marshaler and json.Unmarshaler work with []byte: MarshalJSON must allocate and return a new slice, which the caller then re-parses to validate it. v2 adds two interfaces that work with the streaming encoder and decoder instead:

type MarshalerTo interface {
	MarshalJSONTo(*jsontext.Encoder) error
}

type UnmarshalerFrom interface {
	UnmarshalJSONFrom(*jsontext.Decoder) error
}

If a type implements both the old and new methods, the new ones win. Here's a Point that is encoded as a two-element array [x, y] instead of an object:

package main

import (
	"fmt"
	"log"

	jsonv1 "encoding/json"
	"encoding/json/jsontext"
	"encoding/json/v2"
)

// Point is encoded as a two-element array: [x, y]
type Point struct {
	X, Y int64
}

func (p Point) MarshalJSONTo(enc *jsontext.Encoder) error {
	if err := enc.WriteToken(jsontext.BeginArray); err != nil {
		return err
	}
	if err := enc.WriteToken(jsontext.Int(p.X)); err != nil {
		return err
	}
	if err := enc.WriteToken(jsontext.Int(p.Y)); err != nil {
		return err
	}
	return enc.WriteToken(jsontext.EndArray)
}

func (p *Point) UnmarshalJSONFrom(dec *jsontext.Decoder) error {
	if tok, err := dec.ReadToken(); err != nil {
		return err
	} else if tok.Kind() != '[' {
		return fmt.Errorf("point: expected array, got %v", tok.Kind())
	}
	var xy [2]int64
	for i := range xy {
		tok, err := dec.ReadToken()
		if err != nil {
			return err
		}
		if tok.Kind() != '0' {
			return fmt.Errorf("point: expected number, got %v", tok.Kind())
		}
		if xy[i], err = tok.Int(); err != nil {
			return fmt.Errorf("point: %w", err)
		}
	}
	if tok, err := dec.ReadToken(); err != nil {
		return err
	} else if tok.Kind() != ']' {
		return fmt.Errorf("point: expected 2 elements")
	}
	p.X, p.Y = xy[0], xy[1]
	return nil
}

type Shape struct {
	Name   string  `json:"name"`
	Points []Point `json:"points"`
}

func main() {
	s := Shape{Name: "triangle", Points: []Point{{0, 0}, {4, 0}, {0, 3}}}
	b, err := json.Marshal(s)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(b))

	var s2 Shape
	if err := json.Unmarshal(b, &s2); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%+v\n", s2)

	for _, in := range []string{
		`{"name":"x","points":[[1,2,3]]}`,
		`{"name":"x","points":[[1.5,2]]}`,
		`{"name":"x","points":[{"x":1}]}`,
	} {
		var s3 Shape
		fmt.Println(json.Unmarshal([]byte(in), &s3))
	}

	// encoding/json (v1) uses the same methods
	b1, _ := jsonv1.Marshal(s)
	fmt.Println("v1:", string(b1))
}
{"name":"triangle","points":[[0,0],[4,0],[0,3]]}
{Name:triangle Points:[{X:0 Y:0} {X:4 Y:0} {X:0 Y:3}]}
json: cannot unmarshal into Go main.Point within "/points/0": point: expected 2 elements
json: cannot unmarshal into Go main.Point within "/points/0": point: jsontext.Token(1.5).Int error: invalid syntax
json: cannot unmarshal into Go main.Point within "/points/0": point: expected array, got {
v1: {"name":"triangle","points":[[0,0],[4,0],[0,3]]}

Rules for implementations:

Errors are wrapped with the location (within "/points/0"), which you get for free. As the last line shows, encoding/json (v1) uses these methods too, since in Go 1.27 v1 is implemented on top of v2.

How much does it matter? Here's the number of allocations for marshaling 1000 points with each interface:

package main

import (
	"fmt"
	"io"
	"strconv"
	"testing"

	"encoding/json/jsontext"
	"encoding/json/v2"
)

type Point struct{ X, Y int64 }

func (p Point) MarshalJSONTo(enc *jsontext.Encoder) error {
	enc.WriteToken(jsontext.BeginArray)
	enc.WriteToken(jsontext.Int(p.X))
	enc.WriteToken(jsontext.Int(p.Y))
	return enc.WriteToken(jsontext.EndArray)
}

// OldPoint uses the v1-style Marshaler interface: every call
// must return a freshly allocated []byte.
type OldPoint struct{ X, Y int64 }

func (p OldPoint) MarshalJSON() ([]byte, error) {
	b := []byte{'['}
	b = strconv.AppendInt(b, p.X, 10)
	b = append(b, ',')
	b = strconv.AppendInt(b, p.Y, 10)
	return append(b, ']'), nil
}

func main() {
	pts := make([]Point, 1000)
	old := make([]OldPoint, 1000)
	enc := jsontext.NewEncoder(io.Discard)

	fmt.Println("MarshalJSONTo allocs:", testing.AllocsPerRun(100, func() {
		json.MarshalEncode(enc, pts)
	}))
	fmt.Println("MarshalJSON allocs:  ", testing.AllocsPerRun(100, func() {
		json.MarshalEncode(enc, old)
	}))
}
MarshalJSONTo allocs: 2
MarshalJSON allocs:   2002

MarshalJSON costs two allocations per call (one of them is the returned slice), while MarshalJSONTo writes directly into the encoder's buffer. For types that appear in large slices or hot paths, implement the new interfaces. For one-off types, MarshalJSON is still fine; see Custom JSON marshaling.

Summary

For the simple case of decoding a whole file into a struct, Decoding JSON from a file is all you need.

Feedback about page:

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



Table Of Contents