Skip to content

JSON, XML, Struct Tags, Encoder/Decoder, Base64 ​

"The names within an object SHOULD be unique." — RFC 8259, The JavaScript Object Notation (JSON) Data Interchange Format, Section 4

Summary: encoding/json maps Go values to JSON text with reflection and struct tags; the sharp edges are tag semantics, float64 numbers, null versus absent, unknown fields, duplicate keys and unbounded input. encoding/xml, encoding/base64, encoding/hex, encoding/gob and encoding/csv follow the same Marshal/Unmarshal and streaming shapes. Focus: Tags (omitempty, omitzero, string, -), matching rules, any and json.Number, json.RawMessage, Encoder/Decoder streams, custom marshalers and TextMarshaler enums, nullable fields, error types with offsets, performance and the encoding/json/v2 experiment, request-size limits, XML attributes/namespaces/tokens, Base64 variants and padding, gob and CSV. Learning goal: Decode untrusted JSON safely and predictably, produce JSON that a JavaScript or PHP client reads without surprises, and pick the right encoding package and variant without guessing.

This page owns the encoding packages of the standard library as a Go developer uses them. It does not re-teach the byte-level theory of Base64, hex and percent-encoding (that is Binary-to-Text Encoding), the comparison of JSON with Protobuf, MessagePack, Avro and CBOR (Serialization Formats), or struct and tag basics (Structs, Methods, Embedding & Struct Tags). It links the Protobuf toolchain (gRPC & Protobuf in Go), the reader/writer plumbing (The io Package), the time formats (time.Time and Formatting) and the HTTP handler side (net/http). Everything marked "real output" was produced by the snippets on this machine with Go 1.27.4; module directive go 1.24.

Page map ​

If you are looking forGo to
Tables you can memorise in one minuteEverything in one minute
Why a reflection-based codec exists and what it costsWhy it exists
RFC 8259, the 2011 blog post, v2Where it comes from
How Marshal and Unmarshal map typesMarshal and Unmarshal
omitempty, omitzero, string, -Struct tags
Case-insensitive keys, unexported and embedded fieldsMatching rules
map[string]any, float64, json.Number, UseNumberDecoding into any
json.RawMessage and envelopesRawMessage
Encoder, Decoder, More, DisallowUnknownFields, SetEscapeHTML, SetIndentStreams
MarshalJSON, UnmarshalJSON, TextMarshalerCustom marshalers
time.Time, enums, DurationTime and enums
*T, sql.NullString, null versus absentNullable fields
SyntaxError, UnmarshalTypeError, OffsetErrors
jsoniter, sonic, easyjson, reflection costPerformance
GOEXPERIMENT=jsonv2, encoding/json/v2The v2 experiment
MaxBytesReader, depth, duplicate keysSecurity
encoding/xml tags, namespaces, TokenXML
StdEncoding, URLEncoding, RawStdEncoding, paddingBase64
encoding/hex, encoding/gob, encoding/csvHex, gob and CSV
JSON Schema, Protobuf, MessagePackSchemas and other formats
Every knob and every error textMechanics
Ready-made patternsSolving the classic problems
Which package for which jobChoosing
Monolith to distributed systemIn architecture
Reproduce the outputsLab
Wrong beliefs, cheat sheet, every termMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The packages.

PackageIn plain wordsStreaming typeGotcha
encoding/jsonGo value to and from JSON textjson.Encoder, json.DecoderNumbers into any become float64
encoding/xmlGo value to and from XMLxml.Decoder.Tokenxml.Name pins the root; namespaces are matched
encoding/base64Bytes to printable text and backbase64.NewEncoder, NewDecoderFour alphabets/padding variants that do not interoperate
encoding/hexBytes to two hex digits eachhex.NewEncoder, hex.DumperLower-case output; odd length is an error
encoding/gobGo-only binary self-describing formatgob.Encoder, gob.DecoderNot for untrusted input, not for other languages
encoding/csvRecords of string fieldscsv.Reader, csv.WriterQuotes, LazyQuotes, field-count check

The struct tag options (encoding/json).

TagEncoding effectDecoding effectSince
json:"name"Key is nameKey matched to field, case-insensitively1.0
json:"name,omitempty"Dropped when false, 0, nil pointer/interface, empty array/slice/map/stringnone1.0
json:"name,omitzero"Dropped when the value is its type's zero value or IsZero() bool is truenone1.24
json:"name,string"Number/bool/string written as a quoted JSON stringExpects a quoted value1.0
json:"-"Field skippedField ignored1.0
json:"-,"Key is the literal -Matches key -1.0
no tagKey is the Go field nameSame, case-insensitive1.0
unexported fieldSkipped silentlySkipped silently1.0

JSON to Go, through any.

JSONGo dynamic typeWith UseNumber
objectmap[string]anysame
array[]anysame
stringstringsame
numberfloat64json.Number (a string)
true/falseboolsame
nullnilsame

Base64 variants.

EncodingAlphabet 62/63PaddingTypical use
StdEncoding+ /yes (=)MIME, JSON []byte, PEM bodies
RawStdEncoding+ /noCompact binary in text without URLs
URLEncoding- _yesURL-safe values with padding
RawURLEncoding- _noJWT segments, tokens in URLs

Why it exists ​

Programs hold typed values in memory; the network carries bytes. JSON became the default text format because every language reads it, humans can read it, and it needs no schema compiler. Go's encoding/json removes the boilerplate of building that text by hand: you describe the shape once (a struct with tags) and reflection does the walking. The price is a type system mismatch: JSON has one number type, no integers distinct from floats, null as a value, no dates, and objects whose keys may repeat.

ChoiceStrengthWeakness
Reflection-driven codec (encoding/json)Zero generated code, tags next to fieldsCPU and allocation cost, runtime errors for bad tags
Generated codec (easyjson, Protobuf)Fast, schema checked at build timeBuild step, generated files
Hand-written MarshalJSONTotal control, stable wire formatYou own every edge case
Decode into map[string]anyNo struct neededLose types, float64 numbers, no compile-time checks

An everyday picture. A customs form. The struct tag is the box you tick; omitempty is "leave the box blank if there is nothing to declare"; DisallowUnknownFields is the officer who rejects a form with a box that does not exist; json.Number is writing the passport number as text instead of letting someone round it.

Three common misunderstandings, up front ​

  1. "omitempty drops zero values." It drops only the fixed "empty" set (false, 0, nil, empty string/slice/map). A zero time.Time and a zero struct are never empty; that is why Go 1.24 added omitzero.
  2. "JSON numbers are integers or floats like in Go." The JSON text has digits; the receiver decides. Go's any picks float64; JavaScript only has doubles; an int64 above 2^53 silently changes.
  3. "Decoding a bad body returns an error and writes nothing." A syntax error writes nothing, but a type error keeps decoding and leaves the other fields filled.

Where it comes from ​

JSON was derived from JavaScript object literals in the early 2000s (general knowledge, not taken from a page fetched for this chapter); ECMA-404 and RFC 8259 are the standards (RFC 8259 states that it was derived from the ECMAScript Programming Language Standard). RFC 8259 allows implementations to limit number range and precision and notes that "good interoperability can be achieved by implementations that expect no more precision or range than" IEEE 754 binary64 provides; it also says object names SHOULD be unique, which is the whole reason duplicate keys are a security topic. Go's encoding/json shipped with Go 1 in 2012; the official blog post JSON and Go describes the Marshal/Unmarshal model that has not changed since. encoding/xml is the same design for XML 1.0; encoding/base64 implements RFC 4648; encoding/gob is Go's own wire format. Go 1.24 (February 2025) added the omitzero option. Go 1.25 added an experimental encoding/json/v2 and encoding/json/jsontext behind GOEXPERIMENT=jsonv2; the Go blog post A new experimental Go API for JSON explains why. All of this was read from the saved pages listed in References.

The concept catalogue ​

Marshal and Unmarshal Must-know ​

In plain words: json.Marshal(v) turns a Go value into JSON bytes; json.Unmarshal(data, &v) fills a Go value from JSON bytes. You must pass a pointer to Unmarshal.

Common misunderstanding: "Marshal encodes every field." Only exported fields are visible to reflection; Marshal also sorts map keys, encodes []byte as a Base64 string and refuses values with no JSON form.

Definition: func Marshal(v any) ([]byte, error) and func Unmarshal(data []byte, v any) error. Unmarshal first checks that the whole input is valid JSON, then stores into v. Mapping rules: bool to bool; number to any int/uint/float type (overflow is an UnmarshalTypeError); string to string; array to slice/array; object to struct or map[string]T; null to nil pointer/slice/map/interface and a no-op for other types.

Marshal path                         Unmarshal path
1  Marshal(v)                        1  Unmarshal(data, &v)
2  lookup cached encoder for T       2  checkValid(data)        -> SyntaxError, nothing written
3  walk fields with reflect          3  find field by key       -> exact then case-insensitive
4  append to buffer                  4  set value               -> UnmarshalTypeError saved, continue
5  copy to a fresh []byte            5  return first saved error
MarshalGo valuestruct, map, slicetype encoder cachebuilt once per type (reflect)encodeStatebytes.Buffer[]byte JSONUnmarshal[]byte JSONcheckValid scanwhole input, SyntaxErrordecodeStatematch key, set field*T filled inUnmarshalTypeError saved, decoding continuesSyntax errors abort before any field is written; type errors do not.

Real output (the module's demo command) for the struct in the tags snippet:

{"created_by":"ops","version":3,"id":"42","name":"Ada","score":0,"joined":"2026-01-02T03:04:05Z","tags":null,"-":"","NoTag":""}

Real scenario: a handler returns {"id":"42"} for a struct that uses ,string; a worker Marshals a chan field and gets json: unsupported type: chan int; a metrics struct holds math.NaN() and fails with json: unsupported value: NaN.

Input to UnmarshalResultExact error text
{"age":"ten"} into intUnmarshalTypeError, rest still decodedjson: cannot unmarshal string into Go struct field R.age of type int
{"age":1.5} into intUnmarshalTypeErrorjson: cannot unmarshal number 1.5 into Go struct field R.age of type int
{"age":99999999999999999999} into intoverflow, UnmarshalTypeErrorjson: cannot unmarshal number 99999999999999999999 into Go struct field R.age of type int
{"age":1SyntaxErrorunexpected end of JSON input
{"age":1}xSyntaxErrorinvalid character 'x' after top-level value
non-pointer targetInvalidUnmarshalErrorjson: Unmarshal(non-pointer main.R)
nil targetInvalidUnmarshalErrorjson: Unmarshal(nil)
Marshal(math.NaN())UnsupportedValueErrorjson: unsupported value: NaN
Marshal(make(chan int))UnsupportedTypeErrorjson: unsupported type: chan int

Struct tags Must-know ​

In plain words: A struct tag (the json tag, for this package) is a string after the field type that tells encoding/json the JSON key and options. json:"name,omitempty" means "call it name and leave it out when empty".

Common misunderstanding: "omitempty on an int lets me send 0 explicitly." It cannot: a 0 is dropped, so the receiver cannot tell "zero" from "not set". Use a pointer (*int) or omitzero on a type where zero is meaningful to detect.

Definition: the tag value is key,option,option. Options: omitempty (false, 0, nil pointer or interface, empty array/slice/map/string), omitzero (Go 1.24: omit when the value is the zero value of its type, or when its IsZero() bool method returns true; it applies to structs, which omitempty never does), string (quote numbers, bools and strings as JSON strings; only for those kinds), and - (skip). The key -, names a field literally -.

type User struct { ID int64 `json:"id,string"`; Joined time.Time `json:"joined,omitzero"` }
Marshal(User{ID: 42})                    -> {"id":"42"}            (zero Joined omitted)
Marshal(User{ID: 42, Joined: someTime})  -> {"id":"42","joined":"2026-01-02T03:04:05Z"}
Unmarshal({"id":7}, &User{})             -> error: string option wants a quoted number
go
// Package tags shows how struct tags and field rules shape encoding/json output.
package tags

import (
	"encoding/json"
	"time"
)

// Audit is embedded: its exported fields are promoted into the parent object.
type Audit struct {
	CreatedBy string `json:"created_by"`
	Version   int    `json:"version"`
}

// User demonstrates the tag options. Field names are chosen to make each rule visible.
type User struct {
	Audit               // embedded struct: fields are flattened
	ID       int64      `json:"id,string"`        // quoted number: "id":"42"
	Name     string     `json:"name"`             // plain rename
	Email    string     `json:"email,omitempty"`  // dropped when ""
	Age      int        `json:"age,omitempty"`    // dropped when 0 (so 0 is unrepresentable)
	Score    *int       `json:"score,omitempty"`  // dropped when nil, kept when pointing at 0
	Joined   time.Time  `json:"joined,omitzero"`  // Go 1.24: dropped when IsZero() is true
	Deleted  *time.Time `json:"deleted,omitzero"` // nil pointer is zero
	Tags     []string   `json:"tags"`             // nil slice -> null, empty slice -> []
	Password string     `json:"-"`                // never encoded or decoded
	Dash     string     `json:"-,"`               // the literal key "-"
	secret   string     // unexported: ignored silently
	NoTag    string     // key is the Go name: "NoTag"
}

// Encode marshals u compactly.
func Encode(u User) (string, error) {
	b, err := json.Marshal(u)
	return string(b), err
}

// Decode unmarshals data into a User. Key matching is case-insensitive.
func Decode(data string) (User, error) {
	var u User
	err := json.Unmarshal([]byte(data), &u)
	return u, err
}

// HasSecret reports the unexported field so go vet does not flag it as unused.
func (u User) HasSecret() bool { return u.secret != "" }
go
package tags

import (
	"testing"
	"time"
)

func TestEncodeTags(t *testing.T) {
	zero := 0
	u := User{Audit: Audit{CreatedBy: "ops", Version: 3}, ID: 42, Name: "Ada", Password: "x", Dash: "d", Score: &zero, Tags: nil}
	got, err := Encode(u)
	if err != nil {
		t.Fatal(err)
	}
	want := `{"created_by":"ops","version":3,"id":"42","name":"Ada","score":0,"tags":null,"-":"d","NoTag":""}`
	if got != want {
		t.Fatalf("got  %s\nwant %s", got, want)
	}
}

func TestOmitzeroTime(t *testing.T) {
	u := User{Joined: time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC), Tags: []string{}}
	got, _ := Encode(u)
	if want := `"joined":"2026-01-02T03:04:05Z"`; !contains(got, want) || !contains(got, `"tags":[]`) {
		t.Fatalf("unexpected: %s", got)
	}
}

func TestDecodeCaseInsensitive(t *testing.T) {
	u, err := Decode(`{"NAME":"Bob","Id":"7","password":"leak","secret":"leak","CREATED_BY":"x"}`)
	if err != nil {
		t.Fatal(err)
	}
	if u.Name != "Bob" || u.ID != 7 || u.CreatedBy != "x" {
		t.Fatalf("case-insensitive match failed: %+v", u)
	}
	if u.Password != "" || u.HasSecret() {
		t.Fatal("ignored fields must stay empty")
	}
}

func TestStringOptionRejectsBareNumber(t *testing.T) {
	if _, err := Decode(`{"id":7}`); err == nil {
		t.Fatal("expected error: string option requires a quoted number")
	}
}

func contains(s, sub string) bool {
	for i := 0; i+len(sub) <= len(s); i++ {
		if s[i:i+len(sub)] == sub {
			return true
		}
	}
	return false
}

Real scenario: a PATCH DTO with Age int json:"age,omitempty" can never set age to 0; a deleted_at time.Time json:"deleted_at,omitempty" still prints "0001-01-01T00:00:00Z", fixed by omitzero or *time.Time; an ID int64 json:"id,string" keeps JavaScript from rounding it.

Field typeomitempty omits whenomitzero omits when
boolfalsefalse
int, float6400
string""""
*T, anynilnil
[]T, map[K]Vlength 0 (nil or empty)nil only
time.TimeneverIsZero() is true
structneverall fields zero (or IsZero() true)
array [3]intlength 0 onlyall elements zero

Matching rules: case, unexported and embedded fields Important ​

In plain words: When decoding, a JSON key finds its Go field by exact name first, then ignoring case. Fields that start with a lower-case letter are invisible. An embedded struct's fields are lifted into the outer object.

Common misunderstanding: "A private field is simply not required in the JSON." It is also never filled, never an error, and never reported: a client that sends it gets silence.

Definition: Unmarshal matches keys to struct fields case-insensitively (preferring an exact match). Unexported fields are ignored on both sides. Embedded structs (anonymous fields) are flattened; on a name clash the shallower field wins, and between equals at the same depth a tagged field wins, and an unresolvable tie drops all of them without error. An embedded pointer to an unexported struct type cannot be set by Unmarshal and returns an error.

Unmarshal(`{"NAME":"Bob","Id":"7","password":"leak","secret":"leak"}`, &User{})
1  NAME      -> matches json:"name" ignoring case        -> Name = "Bob"
2  Id        -> matches json:"id,string" ignoring case   -> ID = 7
3  password  -> field tagged "-"                         -> ignored
4  secret    -> unexported field                         -> ignored

Real scenario: an upstream sends userId and your tag says user_id; it does not match (underscores are not folded), so the field stays zero with no error. Embedding an Audit struct gives every DTO created_by and version without repeating them.

RuleBehaviourFix when it hurts
Case-insensitive match{"NAME":"x"} fills nameencoding/json/v2 is case-sensitive; or validate keys yourself
Underscore/dash not foldeduser_id is not userIdAdd an exact tag or a custom UnmarshalJSON
Unexported ignoredsilentExport the field or use a DTO
Embedded struct flattenedfields appear at top levelTag the embedded field to nest it: Audit `json:"audit"`
Name conflict, same depth, both taggedboth droppedRename one

Decoding into any, float64 and json.Number Must-know ​

In plain words: If you do not know the shape, decode into any. Objects become map[string]any, arrays []any, numbers float64.

Common misunderstanding: "float64 is fine for any number JSON carries." A float64 has a 53-bit mantissa; an int64 such as 9007199254740993 comes back as 9007199254740992 with no error.

Definition: json.Number is a string type with Float64(), Int64() and String(). Decoder.UseNumber() makes any targets receive json.Number for numbers. A typed int64 field is exact because the digits are parsed directly into the integer.

Unmarshal(`9007199254740993`, &any)           -> float64(9007199254740992)   digits lost
Decoder.UseNumber(); Decode(&any)             -> json.Number("9007199254740993")
Unmarshal(`9007199254740993`, &struct{N int64})-> N = 9007199254740993       exact
go
// Package anyshapes covers decoding into any, float64 precision, json.Number and RawMessage.
package anyshapes

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

// Shapes decodes one document into any and reports the dynamic type of each member.
func Shapes(doc string) (map[string]string, error) {
	var m map[string]any
	if err := json.Unmarshal([]byte(doc), &m); err != nil {
		return nil, err
	}
	out := make(map[string]string, len(m))
	for k, v := range m {
		out[k] = fmt.Sprintf("%T", v)
	}
	return out, nil
}

// AsFloat decodes a number the default way: through float64.
func AsFloat(doc string) (any, error) {
	var v any
	err := json.Unmarshal([]byte(doc), &v)
	return v, err
}

// AsNumber decodes with UseNumber so big integers survive as text.
func AsNumber(doc string) (json.Number, error) {
	dec := json.NewDecoder(bytes.NewReader([]byte(doc)))
	dec.UseNumber()
	var v any
	if err := dec.Decode(&v); err != nil {
		return "", err
	}
	return v.(json.Number), nil
}

// Envelope keeps the payload undecoded until the type is known.
type Envelope struct {
	Type    string          `json:"type"`
	Payload json.RawMessage `json:"payload"`
}

// Paid and Refunded are the two payload shapes.
type Paid struct {
	Amount int `json:"amount"`
}
type Refunded struct {
	Reason string `json:"reason"`
}

// Dispatch decodes the payload according to the envelope type.
func Dispatch(doc string) (any, error) {
	var e Envelope
	if err := json.Unmarshal([]byte(doc), &e); err != nil {
		return nil, err
	}
	switch e.Type {
	case "paid":
		var p Paid
		err := json.Unmarshal(e.Payload, &p)
		return p, err
	case "refunded":
		var r Refunded
		err := json.Unmarshal(e.Payload, &r)
		return r, err
	}
	return nil, fmt.Errorf("unknown event type %q", e.Type)
}
JSON valueGo value inside any{ "a": 1 }[1, 2]"text"true / falsenullmap[string]any[]anystringboolnil9007199254740993float64 9007199254740992json.Number "…993"default: integers above 2^53round to the nearest doubleUseNumber() keeps the digits

Real output from the module's demo command:

float64: 9007199254740992
UseNumber: 9007199254740993

Real scenario: a payment id passed through a generic gateway that decodes into map[string]any and re-marshals it changes the last digits; the fix is UseNumber or typed structs. IDs larger than 2^53 sent to a browser must be sent as strings (,string or a custom type) because JSON.parse has the same limit.

Where the number goesSafe rangeFix beyond it
Go int64 fieldfull 64-bitnone needed
Go any2^53 (about 9.007e15)UseNumber or a typed struct
JavaScript JSON.parse2^53send as string, or use BigInt reviver
PHP json_decodeint up to PHP_INT_MAX, then floatJSON_BIGINT_AS_STRING

json.RawMessage Important ​

In plain words: json.RawMessage is a []byte that keeps a piece of JSON undecoded, so you can look at one field first (the type) and decode the rest later.

Common misunderstanding: "RawMessage is a validated, safe string." It is just bytes: a nil RawMessage marshals as null, and invalid JSON inside one makes Marshal fail, so check before you build one by hand.

Definition: type RawMessage []byte; it implements Marshaler and Unmarshaler. It is the standard way to build envelopes ({"type":..., "payload":...}), to forward a field untouched, and to defer a heavy sub-document.

doc: {"type":"paid","payload":{"amount":500}}
1  Unmarshal into Envelope{Type string; Payload RawMessage}
2  switch Type                      -> "paid"
3  Unmarshal(Payload, &Paid{})     -> Amount = 500

Real scenario: an event bus receives many event types on one topic; a webhook receiver stores the original body for signature verification while decoding it; a proxy rewrites one field and forwards the rest. See Message Design & Schema Evolution for envelope design.

Streams: Encoder, Decoder, More, DisallowUnknownFields Must-know ​

In plain words: json.NewDecoder(r) reads JSON values one after another from an io.Reader; json.NewEncoder(w) writes them to an io.Writer. You use them for HTTP bodies, files and large or endless data.

Common misunderstanding: "Decoder limits the size of the body." It does not. It buffers one value completely; without http.MaxBytesReader a client can send gigabytes. Also, Decode reads only the first value, so trailing garbage after a valid object is silently ignored.

Definition: Decoder.Decode(&v) reads the next value, returns io.EOF at the end of a clean stream. Decoder.Token() returns delimiters and scalars one at a time; Decoder.More() reports whether another element follows in the current array or object. Decoder.DisallowUnknownFields() turns unknown keys into an error. Decoder.UseNumber() as above. Decoder.Buffered() returns the unread remainder; InputOffset() gives the byte position. Encoder.Encode(v) writes the value plus a newline; SetEscapeHTML(false) keeps <, >, & literal (the default writes <, >, &); SetIndent(prefix, indent) pretty-prints.

NDJSON, one value per line                Large array [ {...}, {...}, ... ]
1  dec := NewDecoder(r)                   1  dec.Token()           // [
2  for { dec.Decode(&e)                   2  for dec.More() {
3        io.EOF -> done }                 3      dec.Decode(&e) }   // one element in memory
                                          4  dec.Token()           // ]
go
// Package stream shows Encoder/Decoder over io streams (NDJSON and big arrays).
package stream

import (
	"encoding/json"
	"errors"
	"io"
	"strings"
)

// Event is one record of a stream.
type Event struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
}

// ReadAll decodes concatenated JSON values (NDJSON style) until io.EOF.
func ReadAll(r io.Reader, strict bool) ([]Event, error) {
	dec := json.NewDecoder(r)
	if strict {
		dec.DisallowUnknownFields()
	}
	var out []Event
	for {
		var e Event
		err := dec.Decode(&e)
		if errors.Is(err, io.EOF) {
			return out, nil
		}
		if err != nil {
			return out, err
		}
		out = append(out, e)
	}
}

// ReadArray streams the elements of a top-level JSON array without loading it whole.
func ReadArray(r io.Reader, fn func(Event) error) error {
	dec := json.NewDecoder(r)
	if _, err := dec.Token(); err != nil { // opening [
		return err
	}
	for dec.More() {
		var e Event
		if err := dec.Decode(&e); err != nil {
			return err
		}
		if err := fn(e); err != nil {
			return err
		}
	}
	_, err := dec.Token() // closing ]
	return err
}

// Write encodes events one per line. escapeHTML=false keeps <, > and & literal.
func Write(w io.Writer, events []Event, escapeHTML bool, indent string) error {
	enc := json.NewEncoder(w)
	enc.SetEscapeHTML(escapeHTML)
	if indent != "" {
		enc.SetIndent("", indent)
	}
	for _, e := range events {
		if err := enc.Encode(e); err != nil { // appends "\n"
			return err
		}
	}
	return nil
}

// Trailing reports whether anything but whitespace follows the first value in s.
func Trailing(s string) bool {
	dec := json.NewDecoder(strings.NewReader(s))
	var v any
	if err := dec.Decode(&v); err != nil {
		return false
	}
	return dec.More() || dec.Decode(&v) != io.EOF
}
io.Readerfile, HTTP bodyDecoder buffergrows to one valueToken / More / Decodeone step per callyour handlerone Event at a timeReading a huge array[{...} Decode{...} Decode{...} Decode]TokenMore = trueMore = trueMore = falseTokenMemory stays at one element. json.Unmarshal would hold the whole array plus the whole result.

Real scenario: an export endpoint writes ten million rows with an Encoder per row; an import reads NDJSON from S3; a CLI pretty-prints with SetIndent("", " "); an HTML-in-JSON API turns SetEscapeHTML(false) on so <b> stays readable (and then takes responsibility for where the JSON is embedded).

MethodDoesError / result
Decode(&v)next valueio.EOF at clean end; io.ErrUnexpectedEOF inside a value
Token()next delimiter or scalarjson.Delim, string, float64, bool, nil
More()is there another elementbool
DisallowUnknownFields()unknown key is an errorjson: unknown field "nmae"
UseNumber()numbers into any become json.Numbernone
Encode(v)writes value and \nwrite error
SetEscapeHTML(false)no < escapesnone
SetIndent(p, i)pretty-printed outputnone

Custom marshalers and TextMarshaler Must-know ​

In plain words: Give a type a MarshalJSON and/or UnmarshalJSON method and encoding/json uses it instead of the default. Give it MarshalText/UnmarshalText (the encoding.TextMarshaler interfaces) and it becomes a JSON string and also a valid map key.

Common misunderstanding: "I can put the unmarshal method on a value receiver." UnmarshalJSON and UnmarshalText must have a pointer receiver, otherwise the change is lost on a copy. And an UnmarshalJSON that calls json.Unmarshal on its own type recurses forever; use an alias type.

Definition: Marshaler is MarshalJSON() ([]byte, error); the output must be valid JSON or Marshal returns an error. Unmarshaler is UnmarshalJSON([]byte) error; it receives the exact raw value and it is also called for the literal null. Map keys: string, integer types, or any type implementing encoding.TextMarshaler/TextUnmarshaler. Precedence when encoding: Marshaler before TextMarshaler.

type Status int  // MarshalText / UnmarshalText
1  Marshal(map[Status]int{Closed: 2})   -> {"closed":2}
2  Marshal(Order{Status: Active})       -> {"status":"active"}
3  Unmarshal({"status":"bogus"})        -> error: unknown status "bogus"
go
// Package custom shows MarshalJSON/UnmarshalJSON, TextMarshaler enums and map keys,
// time formats and nullable fields.
package custom

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"strings"
	"time"
)

// Status is an enum stored as an int and exposed as text. Implementing
// encoding.TextMarshaler/TextUnmarshaler makes it work as a JSON value AND as a map key.
type Status int

const (
	Pending Status = iota
	Active
	Closed
)

var names = [...]string{"pending", "active", "closed"}

func (s Status) MarshalText() ([]byte, error) {
	if s < 0 || int(s) >= len(names) {
		return nil, fmt.Errorf("invalid status %d", int(s))
	}
	return []byte(names[s]), nil
}

func (s *Status) UnmarshalText(b []byte) error {
	for i, n := range names {
		if strings.EqualFold(n, string(b)) {
			*s = Status(i)
			return nil
		}
	}
	return fmt.Errorf("unknown status %q", b)
}

// Money serialises as a decimal string so no JS client rounds it.
type Money int64 // minor units (cents)

func (m Money) MarshalJSON() ([]byte, error) {
	return json.Marshal(fmt.Sprintf("%d.%02d", int64(m)/100, int64(m)%100))
}

func (m *Money) UnmarshalJSON(b []byte) error {
	var s string
	if err := json.Unmarshal(b, &s); err != nil {
		return fmt.Errorf("money must be a JSON string: %w", err)
	}
	var whole, frac int64
	if _, err := fmt.Sscanf(s, "%d.%02d", &whole, &frac); err != nil {
		return fmt.Errorf("money %q: %w", s, err)
	}
	*m = Money(whole*100 + frac)
	return nil
}

// Order mixes everything.
type Order struct {
	ID       int64                      `json:"id"`
	Status   Status                     `json:"status"`
	Total    Money                      `json:"total"`
	PerState map[Status]int             `json:"per_state,omitempty"` // keys use MarshalText
	Placed   time.Time                  `json:"placed"`              // RFC 3339 by default
	Note     *string                    `json:"note"`                // null when absent
	Coupon   NullableCoupon             `json:"coupon"`              // generic nullable (Go 1.22)
	Legacy   sql.NullString             `json:"legacy"`              // encodes as {"String":..,"Valid":..}
	TTL      time.Duration              `json:"ttl"`                 // int64 nanoseconds, a classic trap
	Extra    map[string]json.RawMessage `json:"extra,omitempty"`
}

// Optional distinguishes "key absent" from "key is null" from "key has a value".
// Absent: Set is false (UnmarshalJSON is never called). Null: Set true, Valid false.
type Optional[T any] struct {
	Set   bool
	Valid bool
	Value T
}

func (o *Optional[T]) UnmarshalJSON(b []byte) error {
	o.Set = true
	if string(b) == "null" {
		o.Valid = false
		return nil
	}
	o.Valid = true
	return json.Unmarshal(b, &o.Value)
}

// Patch is a PATCH body: only the keys the client sent are applied.
type Patch struct {
	Note Optional[string] `json:"note"`
}

// NullableCoupon wraps sql.Null so it encodes as null or the bare value.
type NullableCoupon struct{ sql.Null[string] }

func (c NullableCoupon) MarshalJSON() ([]byte, error) {
	if !c.Valid {
		return []byte("null"), nil
	}
	return json.Marshal(c.V)
}

func (c *NullableCoupon) UnmarshalJSON(b []byte) error {
	if string(b) == "null" {
		c.Null = sql.Null[string]{}
		return nil
	}
	c.Valid = true
	return json.Unmarshal(b, &c.V)
}
go
package custom

import (
	"database/sql"
	"encoding/json"
	"strings"
	"testing"
	"time"
)

func TestOrderRoundTrip(t *testing.T) {
	in := Order{ID: 1, Status: Active, Total: 1999, PerState: map[Status]int{Closed: 2, Pending: 1},
		Placed: time.Date(2026, 3, 4, 5, 6, 7, 0, time.UTC), TTL: time.Second}
	b, err := json.Marshal(in)
	if err != nil {
		t.Fatal(err)
	}
	s := string(b)
	for _, want := range []string{`"status":"active"`, `"total":"19.99"`, `"per_state":{"closed":2,"pending":1}`,
		`"placed":"2026-03-04T05:06:07Z"`, `"note":null`, `"coupon":null`, `"legacy":{"String":"","Valid":false}`, `"ttl":1000000000`} {
		if !strings.Contains(s, want) {
			t.Errorf("missing %s in %s", want, s)
		}
	}
	var out Order
	if err := json.Unmarshal(b, &out); err != nil {
		t.Fatal(err)
	}
	if out.Status != Active || out.Total != 1999 || out.PerState[Closed] != 2 {
		t.Fatalf("round trip: %+v", out)
	}
}

func TestBadEnumAndMoney(t *testing.T) {
	var o Order
	err := json.Unmarshal([]byte(`{"status":"bogus"}`), &o)
	if err == nil || !strings.Contains(err.Error(), `unknown status "bogus"`) {
		t.Fatalf("got %v", err)
	}
	err = json.Unmarshal([]byte(`{"total":19.99}`), &o)
	if err == nil || !strings.Contains(err.Error(), "money must be a JSON string") {
		t.Fatalf("got %v", err)
	}
	if _, err := json.Marshal(Order{Status: 9}); err == nil {
		t.Fatal("expected marshal error for invalid status")
	}
}

func TestNullVsAbsent(t *testing.T) {
	var absent, null, val Patch
	_ = json.Unmarshal([]byte(`{}`), &absent)
	_ = json.Unmarshal([]byte(`{"note":null}`), &null)
	_ = json.Unmarshal([]byte(`{"note":"hi"}`), &val)
	if absent.Note.Set || !null.Note.Set || null.Note.Valid || !val.Note.Valid || val.Note.Value != "hi" {
		t.Fatalf("%+v %+v %+v", absent, null, val)
	}
}

func TestPlainSQLNullIsAnObject(t *testing.T) {
	b, _ := json.Marshal(struct{ C sql.Null[string] }{})
	if string(b) != `{"C":{"V":"","Valid":false}}` {
		t.Fatalf("got %s", b)
	}
}

func TestNullGeneric(t *testing.T) {
	var o Order
	if err := json.Unmarshal([]byte(`{"coupon":"SAVE"}`), &o); err != nil {
		t.Fatal(err)
	}
	if !o.Coupon.Valid || o.Coupon.V != "SAVE" {
		t.Fatalf("%+v", o.Coupon)
	}
}

Real scenario: money as a decimal string; a status enum shared between database, JSON and logs; a UUID type; a value that must reject numbers where a string is expected so a client cannot send 19.99 as a float.

time.Time, enums and Duration Important ​

In plain words: time.Time is written as an RFC 3339 string; a Duration is written as a number of nanoseconds; an iota enum is written as a number unless you give it text methods.

Common misunderstanding: "time.Duration encodes as \"5s\"." It encodes as 5000000000. The snippet's order has TTL time.Duration and the real output is "ttl":1000000000.

Definition: time.Time implements MarshalJSON with time.RFC3339Nano and UnmarshalJSON expecting RFC 3339 (2026-03-04T05:06:07Z, offsets allowed); a different layout needs a wrapper type. A zero time.Time encodes as 0001-01-01T00:00:00Z. Enums: implement MarshalText/UnmarshalText and validate in the latter.

Go typeDefault JSONSafer wire format
time.TimeRFC 3339 stringsame; use UTC; omitzero for optional
time.Durationinteger nanosecondsa string like "5s" via a wrapper, or integer milliseconds in the name (timeout_ms)
iota enumintegertext via TextMarshaler
[]byteBase64 (StdEncoding) stringsame; document it
map[int]Tkeys become strings "1"same
float64 NaN/Inferrordecide a sentinel or use a string

Nullable fields: pointers, sql.Null and null versus absent Must-know ​

In plain words: JSON has three states for a key: missing, null, and a value. A plain Go field has only two (zero or set).

Common misunderstanding: "A pointer field distinguishes null from missing." It does not: both leave a *T as nil. And **T does not help: null sets the outer pointer to nil as well.

Definition: *T encodes nil as null and decodes null to nil. sql.NullString and sql.Null[T] (Go 1.22) have no JSON methods: they encode as an object ({"String":"","Valid":false} and {"V":"","Valid":false}) — an easy production mistake when a database struct is returned directly. To tell absent from null, use a type that records that UnmarshalJSON ran (which happens for null too, but never for an absent key), like Optional[T] in the snippet.

PATCH body                    Optional[string].Set   .Valid   meaning
{}                            false                  false     leave unchanged
{"note":null}                 true                   false     clear the value
{"note":"hi"}                 true                   true      set to "hi"

Real scenario: a PATCH endpoint that must clear a column when the client sends null but keep it when the key is missing; a response that must send "deleted_at": null explicitly so a client does not guess; an API that returns a sql.NullString straight from database/sql and leaks {"String":...}. See database/sql & pgx.

Representationnil/absent encodes asAbsent vs null on decode
string""cannot tell
*stringnullcannot tell
*string + omitemptykey omittedcannot tell
sql.NullString{"String":"","Valid":false}object, not null
sql.Null[string]{"V":"","Valid":false}object, not null
Optional[string] (snippet)wrapper decidescan tell
json.RawMessagenull for nilcan tell (nil, null, bytes)

Errors: SyntaxError, UnmarshalTypeError and Offset Important ​

In plain words: A body can be wrong in two ways: not JSON at all (syntax), or JSON of the wrong shape (type). The error values carry the position so you can tell the client where.

Common misunderstanding: "err.Error() is a good client message." It leaks Go type names (Go struct field R.age of type int). Classify with errors.As and write your own text.

Definition: *json.SyntaxError has Offset int64 (bytes read before the error). *json.UnmarshalTypeError has Value ("string", "number 1.5"), Type, Offset, Struct, Field (full path in 1.20+) . *json.InvalidUnmarshalError means the target was not a non-nil pointer. *json.UnsupportedTypeError/UnsupportedValueError/MarshalerError come from Marshal. io.EOF from Decoder.Decode means an empty body; io.ErrUnexpectedEOF means a truncated value. Unmarshal of truncated input returns a SyntaxError with unexpected end of JSON input.

go
// Package jsonerrors classifies encoding/json errors and shows the duplicate-key and depth rules.
package jsonerrors

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

// Req is a small request body.
type Req struct {
	Age  int    `json:"age"`
	Name string `json:"name"`
}

// Describe turns a decode error into a client-safe message with a byte offset.
func Describe(err error) string {
	var syn *json.SyntaxError
	var typ *json.UnmarshalTypeError
	var inv *json.InvalidUnmarshalError
	switch {
	case err == nil:
		return "ok"
	case errors.As(err, &syn):
		return fmt.Sprintf("syntax error at byte %d: %v", syn.Offset, syn)
	case errors.As(err, &typ):
		return fmt.Sprintf("field %q wants %s but got JSON %s (offset %d)", typ.Field, typ.Type, typ.Value, typ.Offset)
	case errors.Is(err, io.EOF):
		return "empty body"
	case errors.Is(err, io.ErrUnexpectedEOF):
		return "truncated body"
	case errors.As(err, &inv):
		return "programmer error: " + inv.Error()
	}
	return err.Error()
}

// Parse decodes a body into Req.
func Parse(body string) (Req, error) {
	var r Req
	err := json.Unmarshal([]byte(body), &r)
	return r, err
}

// Nested builds "[[[...]]]" of the given depth.
func Nested(depth int) string {
	b := make([]byte, 0, depth*2)
	for i := 0; i < depth; i++ {
		b = append(b, '[')
	}
	for i := 0; i < depth; i++ {
		b = append(b, ']')
	}
	return string(b)
}

Real output:

field "age" wants int but got JSON string (offset 13)
syntax error at byte 11: invalid character '}' looking for beginning of object key string
ErrorCauseRetry / client message
*json.SyntaxErrorinvalid JSON text400 with the offset
*json.UnmarshalTypeErrorright JSON, wrong type422 naming the field and expected type
*json.InvalidUnmarshalErrornon-pointer or nil targetbug, panic in tests
io.EOF (Decoder)empty body400 "empty body"
io.ErrUnexpectedEOFcut-off body400 "truncated body"
*http.MaxBytesErrorbody exceeds the limit413
json: unknown field "x"DisallowUnknownFields400 naming the key
*json.MarshalerErrora MarshalJSON failed500, log it

Performance and alternative libraries Good to know ​

In plain words: encoding/json uses reflection (a runtime look-up of types) and allocates; it is fast enough for most services and slow for hot paths.

Common misunderstanding: "Switching to a faster JSON library fixes a slow endpoint." Profile first: most latency is I/O, and a faster codec changes behaviour at the edges (HTML escaping, float formatting, duplicate keys).

Definition: per type, the package builds and caches an encoder or decoder tree (sync.Map); each call still goes through reflect. Costs: allocation for the output buffer and strings, float64 formatting, escaping, and for Unmarshal a pre-scan of the whole input. Options: reuse Encoders and buffers (sync.Pool), avoid map[string]any on hot paths, decode into typed structs, stream large arrays. Third-party codecs named in the community: jsoniter (json-iterator/go, drop-in API), sonic (ByteDance, JIT/SIMD for amd64/arm64), easyjson (code generation, no reflection), go-json (goccy). Treat all of them as optional: measure with go test -bench and confirm the edge-case behaviour you rely on. The standard library's own answer is the v2 experiment.

TechniqueGainCost
Typed struct instead of map[string]anyfewer allocations, exact typesneed a schema
Encoder straight to http.ResponseWriterno intermediate []bytepartial output on mid-stream error
json.RawMessage for pass-through fieldsskip decode/encodevalidate separately
easyjson (generated)no reflectiongenerated files, tooling
sonic, jsoniterfaster on benchmarksdependency, subtle behaviour differences
Smaller payloads (omit empties, short keys)less CPU and bytesreadability
Protobuf/MessagePacksmaller, fasternot human-readable, see Serialization Formats

The encoding/json/v2 experiment Good to know ​

In plain words: Go 1.25 shipped a rewrite of the JSON package that you can try with an environment variable. It is faster at decoding and stricter by default. It is still being refined.

Common misunderstanding: "GOEXPERIMENT=jsonv2 is stable and I can import encoding/json/v2 in production." The 1.25 release notes say the design "will continue to evolve"; the import path is only available when the experiment is on.

Definition: with GOEXPERIMENT=jsonv2 at build time two packages exist, encoding/json/v2 and encoding/json/jsontext, and encoding/json itself runs on the new implementation with the same behaviour but possibly different error text. v2 differences from the package documentation: keys match case-sensitively (v1 is case-insensitive); duplicate object names are an error (v1 permits them); omitempty means "encodes as an empty JSON value" and omitzero is the way to omit false, 0 and nil; the string option only applies to numbers; nil slices and maps encode as [] and {}. Options such as MatchCaseInsensitiveNames restore old behaviour.

Build:  GOEXPERIMENT=jsonv2 go test ./...      (Go 1.25+, experiment)
Check:  does any test fail or does an error text assertion change?
Prefer: omitzero over omitempty on bool, number, pointer, interface fields (works in v1 and v2)
Behaviourv1 (encoding/json)v2 (encoding/json/v2)
Key matchingcase-insensitivecase-sensitive
Duplicate namesaccepted, last winserror
omitemptyGo "empty" valuesJSON empty values (null, "", {}, [])
string optionstring, bool, number, pointernumbers only
Nil slice / mapnull[] / {}
Streaming APIEncoder/DecoderMarshalWrite, UnmarshalRead, jsontext
Statusstable, frozenexperiment (1.25), may change

I could not run the v2 package against go 1.24 in this module: on the installed Go 1.27.4 the encoding/json/v2 import requires go 1.27 in go.mod, so the chapter shows the behaviour from the package documentation and does not ship a v2 snippet.

Security: size, depth and duplicate keys Must-know ​

In plain words: A JSON parser is a program that does what a stranger's text tells it. Limit how much it reads, reject what you do not expect, and never trust a field because the key is spelled right.

Common misunderstanding: "Go's decoder is safe from big payloads." It reads the whole value into memory. The only limits built in are a nesting depth of 10000 (exceeded max depth) and, for map keys and values, available memory.

Definition: wrap the request body with http.MaxBytesReader(w, r.Body, n); it returns *http.MaxBytesError and closes the connection after the response. Call DisallowUnknownFields() for strict APIs. Reject trailing data by calling Token() and expecting io.EOF. Duplicate keys: Unmarshal accepts them and the last one wins (real result: {"name":"first","name":"second","NAME":"third"} leaves Name = "third", because case-folding makes the third a match). Two components that disagree about which duplicate wins (a WAF and your service) are a classic smuggling vector; v2 rejects duplicates.

go
// Package safebody decodes an HTTP JSON body with a size cap, strict fields and no trailing data.
package safebody

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
)

// DecodeJSON reads at most max bytes and rejects unknown fields and trailing values.
func DecodeJSON(w http.ResponseWriter, r *http.Request, dst any, max int64) error {
	r.Body = http.MaxBytesReader(w, r.Body, max)
	dec := json.NewDecoder(r.Body)
	dec.DisallowUnknownFields()
	if err := dec.Decode(dst); err != nil {
		var tooBig *http.MaxBytesError
		if errors.As(err, &tooBig) {
			return fmt.Errorf("body larger than %d bytes", tooBig.Limit)
		}
		return err
	}
	if _, err := dec.Token(); !errors.Is(err, io.EOF) {
		return errors.New("body must contain a single JSON value")
	}
	return nil
}
Attack                         Defence
1  50 GB body                  http.MaxBytesReader(w, r.Body, 1<<20)
2  [[[[ ...10 001 deep         depth cap (built in, 10000) + body cap
3  {"role":"user","role":"admin"}  validate after decode; or use v2 / reject duplicates
4  {"isAdmin":true} on a DTO   DisallowUnknownFields; DTO without privileged fields
5  1E400 number                typed int field returns UnmarshalTypeError
RiskWhere it bitesDefence
Unbounded bodymemory exhaustionMaxBytesReader, server ReadTimeout
Deep nestingstack/CPUbuilt-in depth limit 10000, plus size limit
Mass assignmentextra fields bind to privileged struct fieldsseparate input DTO, DisallowUnknownFields
Duplicate keysparser differentials between componentsv2, or a validation pass; keep one parser per trust boundary
HTML in JSON embedded in a pageXSSleave SetEscapeHTML(true); use html/template for pages
Large numbersrounding of IDsUseNumber, typed int64

XML: tags, attributes, namespaces and tokens Important ​

In plain words: encoding/xml is the JSON package's older cousin: same Marshal/Unmarshal idea, with tags that say whether a field is an attribute, element text or nested element.

Common misunderstanding: "XML parsing in Go is vulnerable to XXE like Java's." Go's encoding/xml does not fetch external entities and ignores DTD declarations; an undeclared entity is an error unless you supply Decoder.Entity. You must still bound the input size and the nesting.

Definition: tag forms: xml:"name" (element), xml:"name,attr" (attribute), xml:",chardata" (text), xml:",cdata", xml:",comment", xml:",innerxml" (raw bytes inside the element, not parsed), xml:",any" (catch-all), xml:"a>b" (nested path), xml:",omitempty", xml:"-". XMLName xml.Name pins the element and, with xml:"urn:x name", the namespace; a mismatch returns expected element <order> in name space urn:example:shop but have urn:other. xml.Header is the declaration string. Streaming: Decoder.Token() returns StartElement, EndElement, CharData, Comment, ProcInst, Directive; Decoder.DecodeElement decodes one subtree. Decoder.Strict (default true) rejects malformed XML; Decoder.Entity maps custom entities.

go
// Package xmldemo covers encoding/xml tags, namespaces, innerxml and streaming with Token.
package xmldemo

import (
	"encoding/xml"
	"errors"
	"io"
	"strings"
)

// Item is a child element with an attribute and text content.
type Item struct {
	SKU  string `xml:"sku,attr"`
	Qty  int    `xml:"qty,attr,omitempty"`
	Name string `xml:",chardata"`
}

// Order maps a small document. XMLName pins the root element and namespace.
type Order struct {
	XMLName xml.Name `xml:"urn:example:shop order"`
	ID      string   `xml:"id,attr"`
	Note    string   `xml:",comment"`
	Items   []Item   `xml:"items>item"` // a>b nests without a wrapper struct
	Raw     string   `xml:",innerxml"`  // the raw bytes between <order> and </order>
}

// Parse decodes a document.
func Parse(doc string) (Order, error) {
	var o Order
	err := xml.Unmarshal([]byte(doc), &o)
	return o, err
}

// Marshal produces indented XML with the declaration header.
func Marshal(o Order) (string, error) {
	o.Raw = "" // innerxml would be emitted verbatim and replace the children
	b, err := xml.MarshalIndent(o, "", "  ")
	return xml.Header + string(b), err
}

// CountElements walks a stream token by token; memory stays flat for any document size.
func CountElements(r io.Reader) (map[string]int, error) {
	dec := xml.NewDecoder(r)
	dec.Strict = true
	counts := map[string]int{}
	for {
		tok, err := dec.Token()
		if errors.Is(err, io.EOF) {
			return counts, nil
		}
		if err != nil {
			return counts, err
		}
		if se, ok := tok.(xml.StartElement); ok {
			counts[se.Name.Local]++
		}
	}
}

// ExpandEntities shows that Go leaves unknown entities as errors unless Entity is set.
func ExpandEntities(doc string, custom map[string]string) (string, error) {
	dec := xml.NewDecoder(strings.NewReader(doc))
	dec.Entity = custom
	var v struct {
		Text string `xml:",chardata"`
	}
	err := dec.Decode(&v)
	return v.Text, err
}
<order xmlns="urn:example:shop" id="A1"><!--rush--><items><item sku="X" qty="2">Widget</item>...</items></order>
1  XMLName   <- element order in namespace urn:example:shop
2  ID        <- attribute id
3  Note      <- comment "rush"
4  Items     <- items>item (two elements, each with attr sku, text as Name)
5  Raw       <- everything between <order ...> and </order>

Real scenario: a SOAP-era payment provider, an RSS or Atom feed, a SAML response, a sitemap. Verified in the tests: <a><b></a> gives XML syntax error on line 1: element <b> closed by </a>, and <a>&bogus;</a> gives XML syntax error on line 1: invalid character entity &bogus;. A DOCTYPE that declares &x; does not make &x; known.

TagMeaningExample
xml:"id,attr"attributeid="A1"
xml:",chardata"element textWidget
xml:",innerxml"raw inner byteschildren untouched
xml:",comment"commentrush
xml:"items>item"nested pathwrapper element without a struct
xml:",any"any unmatched childforward compatibility
XMLName xml.Nameelement and namespaceroot check
xml:",cdata"CDATA section on output<![CDATA[...]]>

Base64 Must-know ​

In plain words: Base64 writes any bytes using 64 printable characters. Three bytes become four characters, so output is one third larger; = pads the last group.

Common misunderstanding: "Base64 is encryption." It hides nothing and has no key. And "all Base64 is the same": the standard alphabet has + and /, the URL alphabet has - and _, and a decoder for one rejects the other.

Definition: RFC 4648 defines the standard alphabet and the URL and filename safe alphabet. Go has four ready values: StdEncoding, URLEncoding, RawStdEncoding, RawURLEncoding (Raw means no padding). EncodeToString/DecodeString for slices; NewEncoder(enc, w)/NewDecoder(enc, r) for streams (call Close on the encoder to flush the last partial group). enc.Strict() rejects non-zero trailing padding bits. base64.CorruptInputError carries the offset: illegal base64 data at input byte N. The theory is in Binary-to-Text Encoding.

go
// Package codecs shows base64 variants, hex, gob and csv.
package codecs

import (
	"bytes"
	"encoding/base64"
	"encoding/csv"
	"encoding/gob"
	"encoding/hex"
	"errors"
	"io"
	"strings"
)

// Variants encodes the same bytes with the four common base64 alphabets.
func Variants(b []byte) map[string]string {
	return map[string]string{
		"std":    base64.StdEncoding.EncodeToString(b),
		"rawstd": base64.RawStdEncoding.EncodeToString(b),
		"url":    base64.URLEncoding.EncodeToString(b),
		"rawurl": base64.RawURLEncoding.EncodeToString(b),
	}
}

// StreamEncode base64-encodes r into w without buffering r. Close flushes the final partial block.
func StreamEncode(w io.Writer, r io.Reader) error {
	enc := base64.NewEncoder(base64.StdEncoding, w)
	if _, err := io.Copy(enc, r); err != nil {
		return err
	}
	return enc.Close()
}

// Hex returns lower-case hex and its decoding.
func Hex(b []byte) (string, []byte, error) {
	s := hex.EncodeToString(b)
	back, err := hex.DecodeString(s)
	return s, back, err
}

// Point is a gob-encodable type.
type Point struct{ X, Y int }

// GobRoundTrip encodes and decodes a Point. gob is Go-only and not for untrusted input.
func GobRoundTrip(p Point) (Point, int, error) {
	var buf bytes.Buffer
	if err := gob.NewEncoder(&buf).Encode(p); err != nil {
		return Point{}, 0, err
	}
	n := buf.Len()
	var out Point
	err := gob.NewDecoder(&buf).Decode(&out)
	return out, n, err
}

// ReadCSV streams records one at a time. lazy sets LazyQuotes.
func ReadCSV(src string, lazy bool) ([][]string, error) {
	r := csv.NewReader(strings.NewReader(src))
	r.LazyQuotes = lazy
	r.FieldsPerRecord = 0 // first record fixes the width
	var rows [][]string
	for {
		rec, err := r.Read()
		if errors.Is(err, io.EOF) {
			return rows, nil
		}
		if err != nil {
			return rows, err
		}
		rows = append(rows, rec)
	}
}

// WriteCSV writes records with correct quoting.
func WriteCSV(rows [][]string) (string, error) {
	var b strings.Builder
	w := csv.NewWriter(&b)
	if err := w.WriteAll(rows); err != nil { // WriteAll flushes
		return "", err
	}
	return b.String(), nil
}
3 bytes become 4 characters (24 bits regrouped as 4 x 6 bits)0xFB0xFF0xFE62636362index into the 64-char alphabetAlphabets and padding (RFC 4648)EncodingIndex 62 / 63, paddingbytes FB FF FE 01Use forStdEncoding+ / with =+//+AQ==MIME, JSON []byteRawURLEncoding- _ no padding-__-AQURLs, JWT segments

Real output for bytes FB FF FE 01:

+//+AQ== +//+AQ -__-AQ== -__-AQ

Real scenario: a JWT is three RawURLEncoding segments joined by dots (see JWT Deep Dive); Marshal of []byte is StdEncoding; a data: URI uses StdEncoding; a signed URL token should be RawURLEncoding so it needs no percent-escaping.

TaskUseReason
JSON []byte fieldautomatic StdEncodingbuilt in
Token inside a URL or filenameRawURLEncodingno + / = to escape
MIME or PEMStdEncoding (line breaks added separately)RFC 2045/7468 expect padding
Read input from an unknown sourcetry Raw then Std, or trim =padding is often stripped
Large fileNewEncoder and io.Copyconstant memory
Constant-time comparisondecode, then compare bytesencodings are not canonical across variants

Hex, gob and CSV Good to know ​

In plain words: hex writes each byte as two digits; gob is Go's private binary format between two Go programs; csv reads and writes comma-separated records.

Common misunderstanding: "gob is a fast JSON replacement for any service." It is Go-only, version-sensitive, and decoding untrusted input can allocate heavily; use it for caches and Go-to-Go RPC you control, not across a trust boundary.

Definition: hex.EncodeToString, hex.DecodeString (error encoding/hex: odd length hex string or invalid byte: U+0067 'g'), hex.Dump/Dumper for the xxd layout. gob.NewEncoder(w).Encode(v), gob.NewDecoder(r).Decode(&v); types and field names are sent once per stream; exported fields only; gob.Register for interface values. csv.NewReader(r): Comma, Comment, FieldsPerRecord (0 means the first record fixes the width), LazyQuotes (accept a bare " in an unquoted field), TrimLeadingSpace, ReuseRecord; read with Read in a loop until io.EOF or ReadAll for small files. csv.NewWriter(w): Write, Flush, Error, WriteAll.

csv with LazyQuotes=false:  a,b\nx,y"z\n  -> parse error on line 2, column 4: bare " in non-quoted-field
csv with LazyQuotes=true:                   -> ["x", "y\"z"]
csv with wrong width:       1,2,3 after a,b -> record on line 2: wrong number of fields
PackageFormatCross-languageUseDo not use for
encoding/hextextyesdigests, ids, debuggingcompact transport
encoding/gobbinaryno (Go only)Go-to-Go caches, test fixturesuntrusted input, public APIs
encoding/csvtextyesexports, imports, spreadsheetsnested data
encoding/jsontextyesAPIs, confighuge binary blobs
encoding/xmltextyeslegacy integrations, feedsnew APIs

Schemas and other formats Good to know ​

In plain words: Tags describe the Go side; they do not validate business rules or document the API.

Common misunderstanding: "If it decodes, it is valid." {"age":-5} decodes into an int. Validation (ranges, required fields, enums) is separate work.

Definition: options: write a Validate() method on the DTO; use a validation library on struct tags (go-playground/validator is the common one); validate against a JSON Schema (draft 2020-12) with a library such as santhosh-tekuri/jsonschema or xeipuuv/gojsonschema, or publish an OpenAPI document and generate types. For binary schema-first formats see Serialization Formats, and for Protobuf code generation see gRPC & Protobuf in Go. Library names here are pointers from community practice and were not fetched or verified for this chapter.

Mechanics ​

Every knob, with its default Must-know ​

KnobDefaultEffectWhere
Decoder.DisallowUnknownFields()offunknown key becomes an errorjson.Decoder
Decoder.UseNumber()offnumbers into any become json.Numberjson.Decoder
Encoder.SetEscapeHTMLtrueescape <, >, & as < etc.json.Encoder
Encoder.SetIndentnonepretty-printingjson.Encoder
json.Valid(data)n/asyntax check, no decodingencoding/json
json.Indent, json.Compact, json.HTMLEscapen/areformat existing bytesencoding/json
Max nesting depth10000exceeded max depthbuilt in, not configurable
http.MaxBytesReadernonecaps request bodynet/http
xml.Decoder.Stricttruemalformed XML is an errorxml.Decoder
xml.Decoder.Entitynilcustom entity mapxml.Decoder
csv.Reader.LazyQuotesfalseaccept bare quotescsv.Reader
csv.Reader.FieldsPerRecord0first record fixes widthcsv.Reader
base64.Encoding.Strict()offreject non-zero padding bitsencoding/base64
GOEXPERIMENT=jsonv2offenable v2 packages and new backend (1.25+)build time

Error texts decoded Must-know ​

MessageSourceMeaning
unexpected end of JSON inputSyntaxError from Unmarshaltruncated or empty text
invalid character '}' looking for beginning of object key stringSyntaxErrortrailing comma
invalid character 'x' after top-level valueSyntaxErrortrailing data
json: cannot unmarshal string into Go struct field R.age of type intUnmarshalTypeErrorwrong type
json: unknown field "nmae"Decodertypo or extra key
json: Unmarshal(non-pointer main.R)InvalidUnmarshalErrorforgot &
json: unsupported type: chan intUnsupportedTypeErrorfield has no JSON form
json: unsupported value: NaNUnsupportedValueErrorNaN or Inf
json: error calling MarshalJSON for type X: ...MarshalerErroryour method failed
exceeded max depthSyntaxErrormore than 10000 nested levels
http: request body too large*http.MaxBytesErrorlimit hit
XML syntax error on line 1: element <b> closed by </a>xml.SyntaxErrormismatched tag
illegal base64 data at input byte 6base64.CorruptInputErrorwrong alphabet or padding
encoding/hex: odd length hex stringhexmissing a digit

What goes on the wire Good to know ​

Marshal(map[string]any{"html": "<b>&"})   -> {"html":"<b>&"}       (HTML-escaped by default)
Marshal(R{B: []byte("hi")})                -> {"b":"aGk="}                         (Base64, StdEncoding)
Marshal(map[string]int{"z":1,"a":2})       -> {"a":2,"z":1}                        (keys sorted)
Marshal([]int(nil))                        -> null     Marshal([]int{}) -> []
Marshal(float64(1e21))                     -> 1e+21     Marshal(100.0) -> 100

Solving the classic problems ​

A safe JSON endpoint ​

Cap the size, reject unknown fields, reject trailing data, classify errors. The safebody snippet above does the first three; use Describe from the errors snippet for messages. Test it with httptest (see Testing & Benchmarking).

go
package safebody

import (
	"net/http/httptest"
	"strings"
	"testing"
)

type in struct {
	Name string `json:"name"`
}

func run(body string, max int64) error {
	r := httptest.NewRequest("POST", "/x", strings.NewReader(body))
	return DecodeJSON(httptest.NewRecorder(), r, &in{}, max)
}

func TestSafeBody(t *testing.T) {
	if err := run(`{"name":"a"}`, 100); err != nil {
		t.Fatal(err)
	}
	if err := run(`{"name":"`+strings.Repeat("a", 200)+`"}`, 50); err == nil || err.Error() != "body larger than 50 bytes" {
		t.Fatalf("got %v", err)
	}
	if err := run(`{"nope":1}`, 100); err == nil {
		t.Fatal("unknown field accepted")
	}
	if err := run(`{"name":"a"}{"name":"b"}`, 100); err == nil || err.Error() != "body must contain a single JSON value" {
		t.Fatalf("got %v", err)
	}
}

Envelope with RawMessage ​

Decode the tag, then the payload by type (anyshapes.Dispatch). Unknown types return a clear error rather than a zero struct.

Exact IDs for JavaScript ​

Send 64-bit IDs as strings: the string tag option on an int64 field, or a custom type that marshals as a string and accepts both forms on input.

PATCH with null versus absent ​

Use Optional[T] (snippet) per field; apply only fields where Set is true; clear where Set && !Valid.

Stream a large export ​

Encoder writing one row per Encode into http.ResponseWriter with Content-Type: application/x-ndjson; flush periodically; on error mid-stream you cannot change the status, so end with an error record.

Enums and map keys ​

MarshalText/UnmarshalText on a pointer receiver; validate in UnmarshalText; the same type works as a JSON value, a map key and in flag.TextVar.

Decode an unknown document safely ​

UseNumber, a size cap, and a type switch on map[string]any/[]any/json.Number/string/bool/nil. See Interfaces, Type Assertions, Type Switches & any.

Troubleshooting table ​

SymptomLikely causeCheck
Field always zero after decodeunexported, wrong tag, or underscore/dash mismatchexport it, compare key spelling
0 missing from outputomitempty on a numberuse *int or custom type
"0001-01-01T00:00:00Z" in outputzero time.Time with omitemptyomitzero or *time.Time
Big id off by a few unitsdecoded into anyUseNumber or typed struct
{"String":"","Valid":false} in APIreturned sql.NullStringmap to a DTO with *string
null where [] expectednil sliceinitialise with make([]T, 0)
< in outputHTML escapingSetEscapeHTML(false) if safe
Memory spike on uploadno size capMaxBytesReader
cannot unmarshal object into Go value of type stringschema driftlog the field path from UnmarshalTypeError.Field
illegal base64 dataURL alphabet or missing paddingpick the matching Encoding

Choosing ​

NeedPickReason
Public HTTP API payloadsencoding/json with typed DTOsuniversal, tooling
Unknown or dynamic JSONmap[string]any with UseNumber, or RawMessagekeep digits and defer decoding
Huge arrays or NDJSONDecoder with Token/Moreconstant memory
Hot path, millions per secondgenerated codec or Protobufno reflection
Strict contract, no extrasDisallowUnknownFields or v2reject typos
Legacy partner, SOAP, feedsencoding/xmlthe format they speak
Binary in a URL or tokenRawURLEncodingno escaping
Binary in JSON[]byte (Base64)automatic
Go-to-Go cache entriesencoding/gob or MessagePackcompact, trusted
Spreadsheet exportencoding/csvRFC 4180 style quoting
Cross-language, versionedProtobuf, Avro, see Serialization Formatsschema evolution

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

DTO structs live next to handlers; one encoding/json configuration; errors become 400 or 422. The simplest correct usage is typed structs with tags, MaxBytesReader, DisallowUnknownFields and a Validate() method. Database models and API models stay separate so a sql.NullString never reaches the wire.

Modular monolith and multiple databases ​

Modules exchange DTOs, not database structs. A shared api package defines the wire types and their custom marshalers (money, IDs, enums), so every module encodes Status identically. Each module owns its tag names; renaming a Go field must not rename a JSON key, which is why tags are written explicitly.

Microservices ​

JSON crosses service boundaries, so the contract matters more than the Go type. Rules that survive: add fields, never reuse or retype a key; accept unknown fields from newer producers (do not use DisallowUnknownFields on consumers of internal events, use it on public request bodies); version with a field or a path; carry an envelope (type, version, payload as RawMessage). For service-to-service calls with a schema, see gRPC & Protobuf in Go; for event design see Message Design & Schema Evolution.

order-service  -- POST /orders  {"id":"9007199254740993"}  --> payment-service
    typed int64 on both ends, id sent as string                 decode with ,string
order-service  -- event  {"type":"order.paid","v":2,"payload":{...}} --> broker --> mailer
    RawMessage payload, mailer ignores unknown fields

Distributed data: replicas, caches, NAT and containers ​

Cached JSON blobs outlive the code that wrote them: a cache entry written by version N is read by version N+1, so adding a field is safe and removing or retyping one is not; store a schema version in the key or the value. Do not use gob in a shared cache across versions. JSON in a database column (jsonb) is decoded by your Go code, so the same tag and null rules apply; see database/sql & pgx. Replicas make no difference to encoding but duplicate keys and number rounding become cross-service bugs.

Scaling path: 1×, 10×, 100× ​

LoadConcernAction
1×Correctnesstyped DTOs, size cap, error classification
10×Allocations show in profilesreuse buffers, avoid map[string]any, stream exports
100×Codec CPU dominatesgenerated codecs or Protobuf for internal hops, test GOEXPERIMENT=jsonv2 on your benchmark, compress responses
sql
-- Where JSON ends up: a column the Go DTO round-trips through. jsonb keeps one value per
-- duplicate key (the last), like encoding/json, and stores numbers as numeric (exact).
CREATE TABLE events (
  id         bigint PRIMARY KEY,
  type       text        NOT NULL,
  payload    jsonb       NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);
SELECT payload ->> 'amount' AS amount FROM events WHERE type = 'paid';

Go ​

Example ​

Every package in this chapter has the same two faces: a whole-value pair (Marshal/Unmarshal, EncodeToString/DecodeString) and a streaming pair (NewEncoder/NewDecoder). The decode-a-request recipe combines them with the limits from Security:

go
func handler(w http.ResponseWriter, r *http.Request) {
	var in CreateOrder
	if err := safebody.DecodeJSON(w, r, &in, 1<<20); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	// ... use in
}

The Go angle ​

The codec is reflection plus tags, not code generation, so the contract is in the struct definition and failures are values you classify with errors.As (see Errors, Wrapping, Panic, Recover & Defer). Interfaces (Marshaler, TextMarshaler) are the extension points, and reflection details are in reflect: When and How.

For PHP/Laravel developers ​

PHPGoNote
json_encode($v)json.Marshal(v)PHP arrays are both lists and maps; Go types are explicit
json_decode($s, true)Unmarshal into map[string]anyPHP integers stay int; Go any gives float64
JSON_THROW_ON_ERRORalways check errwithout the flag PHP returns null on failure and you need json_last_error()
JSON_BIGINT_AS_STRINGUseNumberkeep large integers exact
JSON_UNESCAPED_SLASHES, JSON_HEX_TAGSetEscapeHTML(false)Go escapes <, >, & by default; PHP does not
JSON_PRETTY_PRINTSetIndent / MarshalIndent
JsonSerializable::jsonSerialize()MarshalJSON()PHP returns data to encode; Go returns the final bytes
API Resource / toArray()a DTO struct with tagssame role
base64_encode, base64_decode($s, true)StdEncodingPHP strict mode ~ Go's strictness; URL variant needs strtr in PHP
simplexml_load_stringxml.Unmarshallibxml external-entity loading is off by default in current PHP
php
$data = json_decode($body, true, 512, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING);
return response()->json($payload, 200, [], JSON_UNESCAPED_UNICODE);

Lab ​

All outputs below come from running the module on the host; nothing needs Docker or a network. Run from docs/snippets/go/json-xml-encoding/go with Go 1.24 or newer (export PATH=/opt/homebrew/bin:$PATH on this machine).

  1. Run the demo: go run ./demo. Real output:
{"created_by":"ops","version":3,"id":"42","name":"Ada","score":0,"joined":"2026-01-02T03:04:05Z","tags":null,"-":"","NoTag":""}
float64: 9007199254740992
UseNumber: 9007199254740993
field "age" wants int but got JSON string (offset 13)
syntax error at byte 11: invalid character '}' looking for beginning of object key string
+//+AQ== +//+AQ -__-AQ== -__-AQ
  1. Run the tests with the race detector: go test -race -count=1 ./.... Real output (times vary):
ok  	academy/json-xml-encoding/anyshapes	1.362s
ok  	academy/json-xml-encoding/codecs	1.349s
ok  	academy/json-xml-encoding/custom	1.349s
ok  	academy/json-xml-encoding/jsonerrors	1.372s
ok  	academy/json-xml-encoding/safebody	1.324s
ok  	academy/json-xml-encoding/stream	1.399s
ok  	academy/json-xml-encoding/tags	1.399s
ok  	academy/json-xml-encoding/xmldemo	1.395s
  1. Change omitzero to omitempty on Joined in tags.go and run go test ./tags. The TestOmitzeroTime test still passes, but encode a zero User and you will see "joined":"0001-01-01T00:00:00Z".
  2. Run the whole module under the experiment: GOEXPERIMENT=jsonv2 go test ./.... Expected, not run here for the failing cases: tests that assert error text or duplicate-key tolerance may differ; the tags package passed under the experiment on this machine.
  3. Serve safebody from a handler and curl -d a 2 MB body against a 1 MB cap. Expected, not run: HTTP 413 from your handler mapping *http.MaxBytesError.
  4. Compare go test -bench of json.Unmarshal into a struct and into map[string]any on your own payload; expected, not run: the struct is several times faster with fewer allocations.

Common misconceptions ​

BeliefReality
omitempty omits zero valuesit omits a fixed "empty" set; zero time.Time and structs stay, use omitzero
Pointer fields tell null from absentboth are nil; use a type that records that UnmarshalJSON ran
map[string]any keeps my numbersthey become float64; digits beyond 2^53 are lost
A decode error means nothing was writtentype errors keep decoding; only syntax errors write nothing
Decoder caps the body sizeit buffers a whole value; use http.MaxBytesReader
Decode rejects trailing garbageit reads one value; check for io.EOF with Token()
Unknown JSON keys are an errorignored unless DisallowUnknownFields
JSON keys are case-sensitivev1 matches case-insensitively; v2 does not
sql.NullString marshals to a string or nullit marshals to an object with String and Valid
time.Duration marshals as "5s"it marshals as integer nanoseconds
Base64 encryptsit is reversible encoding; padding and alphabet differ per variant
Go's XML parser is open to XXEit does not fetch external entities; limit size and depth anyway
gob is a safe fast JSON replacementGo-only and unsafe for untrusted input
A faster JSON library is always a drop-inescaping, float output and duplicate-key handling differ

Cheat sheet ​

TopicRemember
Pointer to Unmarshaljson.Unmarshal(data, &v), always a non-nil pointer
Tag syntaxjson:"name,omitempty"; - skips; string quotes numbers
Zero time omitomitzero (Go 1.24) or *time.Time
Numbers in anyfloat64; use UseNumber above 2^53
Unknown fieldsdec.DisallowUnknownFields()
Body caphttp.MaxBytesReader(w, r.Body, n)
Trailing datadec.Token() must return io.EOF
Stream arraysToken, then for dec.More() { Decode }, then Token
Enum as textMarshalText/UnmarshalText (pointer receiver for unmarshal)
Null versus absentcustom Optional[T] with UnmarshalJSON
Error classificationerrors.As to *json.SyntaxError, *json.UnmarshalTypeError (has Offset)
HTML escapingon by default; SetEscapeHTML(false) to turn off
Base64 in URLsRawURLEncoding, no padding
XML attributexml:"id,attr"; text xml:",chardata"
v2GOEXPERIMENT=jsonv2, Go 1.25+ experiment, stricter
gobGo-only, never for untrusted data
CSV quotesLazyQuotes = true accepts a bare "

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A struct has Age int json:"age,omitempty". A client sends {"age":0} and your service stores it. What does the reply contain, and why can the client not tell the age was received? Must-know ​

Answer

Answer: The reply omits age because 0 is "empty" for omitempty. Use a *int, or make the response type not use omitempty, so zero is represented.

2 — Why does json.Unmarshal([]byte("9007199254740993"), &v) into any return 9007199254740992, and how do you keep the digits? Important ​

Answer

Answer: Numbers decode to float64, which has a 53-bit mantissa. Use Decoder.UseNumber() (result is json.Number) or decode into an int64 field.

3 — How do you detect "the key was absent" versus "the key was null" for a PATCH field? Must-know ​

Answer

Answer: A *T cannot; both give nil. Use a wrapper type with UnmarshalJSON that sets Set = true; absent keys never call it, null calls it with the bytes null.

4 — What does DisallowUnknownFields not protect against? Important ​

Answer

Answer: Trailing values after the first object, oversized bodies, duplicate keys, and wrong values for known fields. Combine with MaxBytesReader, a Token() check for io.EOF, and validation.

5 — Write the loop that reads NDJSON from a reader. Must-know ​

Answer

Answer: dec := json.NewDecoder(r); for { var e T; if err := dec.Decode(&e); errors.Is(err, io.EOF) { break } else if err != nil { return err }; use(e) }.

6 — A map keyed by an iota enum should encode as {"closed":2}. What must the enum type implement? Good to know ​

Answer

Answer: encoding.TextMarshaler and TextUnmarshaler (MarshalText, UnmarshalText on a pointer receiver). encoding/json uses them for values and for map keys.

7 — A handler returns a sql.NullString field and the client sees {"String":"","Valid":false}. Why, and what is the fix? Must-know ​

Answer

Answer: sql.NullString has no JSON methods, so it encodes as a struct. Map to a DTO with *string or give it MarshalJSON.

8 — Which base64 encoding do JWT segments use, and what happens if you decode one with StdEncoding? Important ​

Answer

Answer: RawURLEncoding (URL alphabet, no padding). StdEncoding fails on -/_ or missing padding with illegal base64 data at input byte N.

9 — Is encoding/xml vulnerable to external entity expansion? Important ​

Answer

Answer: It does not fetch external entities; DOCTYPE declarations are not expanded, and an unknown entity is an error unless Decoder.Entity is set. Still cap size and depth.

10 — What changes if you build with GOEXPERIMENT=jsonv2? Good to know ​

Answer

Answer: Go 1.25+ exposes encoding/json/v2 and jsontext, and encoding/json runs on the new implementation with the same behaviour but possibly different error texts. v2 is case-sensitive, rejects duplicate names and redefines omitempty and string.

Glossary ​

TermMeaning
encoding/jsonStandard library JSON codec
MarshalGo value to bytes
UnmarshalBytes into a Go value (needs a pointer)
Struct tagString after a field type, read by reflection
json tagjson:"name,options"
omitemptyDrop false, 0, nil, empty string/slice/map
omitzeroDrop the zero value or IsZero() true (Go 1.24)
string optionQuote a number as a JSON string
json:"-"Skip the field
Case-insensitive matchingv1 key lookup ignoring case
Unexported fieldLower-case field, invisible to the codec
Embedded structAnonymous field whose fields are flattened
json.RawMessageUndecoded JSON bytes
json.NumberNumber kept as text
UseNumberDecoder option producing json.Number
float64Default Go type for JSON numbers in any
map[string]anyGeneric JSON object
Encoder / DecoderStream codecs over io.Writer / io.Reader
Decode loopRepeated Decode until io.EOF
MoreIs another element present
DisallowUnknownFieldsUnknown keys become errors
SetEscapeHTMLToggle < escaping
SetIndentPretty-print
MarshalJSON / UnmarshalJSONCustom JSON methods
TextMarshalerMarshalText; string form and map keys
Enum JSONInteger by default, text via TextMarshaler
NullableJSON null representable in Go
Pointer field*T; nil encodes as null
sql.NullStringDatabase nullable, no JSON methods
SyntaxErrorInvalid JSON text, has Offset
UnmarshalTypeErrorWrong JSON type, has Offset and Field
OffsetByte position of the error
Reflection costRuntime type inspection overhead
jsoniterThird-party JSON codec
sonicThird-party JIT/SIMD JSON codec
easyjsonCode-generating JSON codec
json/v2encoding/json/v2, experiment in 1.25
GOEXPERIMENT=jsonv2Build-time switch for v2
MaxBytesReaderLimits an HTTP request body
Duplicate keysSame name twice in one object
encoding/xmlXML codec
xml tagxml:"name,attr" style
attrXML attribute option
chardataXML element text option
innerxmlRaw inner XML option
NamespaceXML name qualifier (urn:...)
xml.NameStruct holding space and local name
Decoder.TokenPull one XML token
Entity expansionReplacing &x;; Go does not fetch external ones
encoding/base64RFC 4648 codec
StdEncoding+ / with padding
URLEncoding- _ with padding
RawStdEncoding+ / without padding
Padding= characters completing the last group
NewEncoderStreaming Base64 writer; needs Close
encoding/hexHex codec
encoding/gobGo-only binary codec
encoding/csvCSV reader/writer
LazyQuotesAccept a bare quote in unquoted fields
JSON SchemaSchema language for validating JSON
json_encodePHP encoder
JSON_THROW_ON_ERRORPHP flag to throw instead of returning null
JsonSerializablePHP interface for custom encoding

References ​

Built by Morteza Negahi