Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Encoding and Data Formats

Go json.Encoder and json.Decoder types

Reference for Go json.Encoder and json.Decoder: stream JSON to writers and from readers, SetIndent, SetEscapeHTML, DisallowUnknownFields, UseNumber and Token.

json.Encoder writes JSON values to an io.Writer; json.Decoder reads JSON values from an io.Reader. Unlike Marshal and Unmarshal they work on streams: an HTTP request body, a file, a network connection, or a sequence of values separated by whitespace (often called JSON Lines or NDJSON).

They also expose options the one-shot functions lack, such as rejecting unknown fields, keeping exact numbers and turning HTML escaping off.

Go
json.NewEncoder(os.Stdout).Encode(v)
err := json.NewDecoder(r.Body).Decode(&v)

Try it

Go Encoder options and a stream of values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Decoding many values, strictly

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
func NewEncoder(w io.Writer) *Encoder
func (enc *Encoder) Encode(v any) error
func (enc *Encoder) SetIndent(prefix, indent string)
func (enc *Encoder) SetEscapeHTML(on bool)

func NewDecoder(r io.Reader) *Decoder
func (dec *Decoder) Decode(v any) error
func (dec *Decoder) DisallowUnknownFields()
func (dec *Decoder) UseNumber()
func (dec *Decoder) More() bool
func (dec *Decoder) Token() (Token, error)
func (dec *Decoder) Buffered() io.Reader
func (dec *Decoder) InputOffset() int64
Method Description
Encode(v) Writes the JSON for v followed by a newline.
SetIndent Pretty-prints like MarshalIndent.
SetEscapeHTML(false) Stops escaping <, > and &.
Decode(v) Reads the next JSON value into v (a pointer). Returns io.EOF when no values remain.
DisallowUnknownFields Makes unknown object keys an error.
UseNumber Decodes numbers into json.Number when the destination is any.
More Reports whether another element remains in the current array or object.
Token Returns the next token: delimiters (json.Delim), bool, float64, Number, string or nil.

Errors. Decode returns io.EOF at a clean end, io.ErrUnexpectedEOF if the stream stops in the middle of a value, plus the same syntax and type errors as Unmarshal.

Usage notes

  • Trailing data is not checked. json.NewDecoder(r).Decode(&v) happily ignores everything after the first value. To insist on exactly one value, call dec.More() or try a second Decode and expect io.EOF.
  • Always limit untrusted bodies: wrap r.Body in http.MaxBytesReader before creating the decoder.
  • Encoder newline: Encode ends with \n, which is what you want for NDJSON but sometimes surprises tests comparing against Marshal output.
  • Large arrays without loading everything: read the opening [ with Token, then loop for dec.More() { dec.Decode(&item) }, then read the closing ].
  • Encoding errors may leave partial output on the writer; Marshal first avoids that at the cost of buffering.
  • Buffering: the decoder reads ahead from the reader. Use Buffered() if you need the bytes it has consumed but not parsed.
  • Not safe for concurrent use; give each goroutine its own, or guard with a mutex.