Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Encoding and Data Formats

The Go encoding/json package

Overview of Go's encoding/json package: Marshal, Unmarshal, Encoder, Decoder, struct tags, RawMessage, Indent, Valid, custom marshalers and error types.

encoding/json converts Go values to JSON text and back. json.Marshal turns a value into bytes, json.Unmarshal fills a value from bytes, and json.NewEncoder / json.NewDecoder do the same on streams such as files and HTTP bodies.

Struct fields are matched to JSON object keys by name or by a struct tag. Only exported fields take part. Types can take over their own encoding by implementing json.Marshaler / json.Unmarshaler (or encoding.TextMarshaler).

Go
b, _ := json.Marshal(map[string]int{"a": 1})
fmt.Println(string(b)) // {"a":1}

Try it

Go Round trip with a struct

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 Unknown shapes, validation and errors

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 Marshal(v any) ([]byte, error)
func MarshalIndent(v any, prefix, indent string) ([]byte, error)
func Unmarshal(data []byte, v any) error
func Valid(data []byte) bool
func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error
func Compact(dst *bytes.Buffer, src []byte) error
func HTMLEscape(dst *bytes.Buffer, src []byte)

func NewEncoder(w io.Writer) *Encoder
func NewDecoder(r io.Reader) *Decoder

type Marshaler interface   { MarshalJSON() ([]byte, error) }
type Unmarshaler interface { UnmarshalJSON([]byte) error }
type RawMessage []byte
type Number string
Name Description
Marshal, MarshalIndent Value to JSON bytes (compact or indented).
Unmarshal JSON bytes into a pointer to a value.
Encoder, Decoder Streaming API: many values, SetIndent, DisallowUnknownFields, UseNumber, More, Token.
RawMessage Bytes kept undecoded until you need them.
Number Exact numeric text, produced by Decoder.UseNumber.
Valid, Indent, Compact, HTMLEscape Helpers working on JSON text.
Errors *SyntaxError, *UnmarshalTypeError, *InvalidUnmarshalError, *UnsupportedTypeError, *UnsupportedValueError, *MarshalerError.

Usage notes

  • Type mapping: bool, strings, numbers, nil pointers/interfaces/maps/slices (null), slices and arrays ([...]), maps with string, integer or TextMarshaler keys ({...}), structs ({...}). []byte becomes a base64 string. Channels, functions and complex numbers cannot be encoded.
  • Map keys are sorted on output, so Marshal of a map is deterministic.
  • Case-insensitive matching: on decoding, a key matches a field name ignoring case if there is no exact tag match. Unknown keys are ignored unless you call DisallowUnknownFields.
  • Numbers into any become float64, losing precision above 2^53. Use UseNumber, a typed field, or json.Number.
  • time.Time encodes as an RFC 3339 string, time.Duration as an integer of nanoseconds, and error values as {} (they have no exported fields).
  • Unmarshal needs a pointer. Passing a value returns an *InvalidUnmarshalError.
  • Performance: reflection-based and allocation-heavy. For hot paths cache decoded structs, stream with Decoder, or consider generated code. Go 1.25 added an experimental faster encoding/json/v2 (build tag GOEXPERIMENT=jsonv2); the stable API here is unchanged.
  • Security: limit body sizes (http.MaxBytesReader) before decoding untrusted input.