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 for | Go to |
|---|---|
| Tables you can memorise in one minute | Everything in one minute |
| Why a reflection-based codec exists and what it costs | Why it exists |
| RFC 8259, the 2011 blog post, v2 | Where it comes from |
How Marshal and Unmarshal map types | Marshal and Unmarshal |
omitempty, omitzero, string, - | Struct tags |
| Case-insensitive keys, unexported and embedded fields | Matching rules |
map[string]any, float64, json.Number, UseNumber | Decoding into any |
json.RawMessage and envelopes | RawMessage |
Encoder, Decoder, More, DisallowUnknownFields, SetEscapeHTML, SetIndent | Streams |
MarshalJSON, UnmarshalJSON, TextMarshaler | Custom marshalers |
time.Time, enums, Duration | Time and enums |
*T, sql.NullString, null versus absent | Nullable fields |
SyntaxError, UnmarshalTypeError, Offset | Errors |
jsoniter, sonic, easyjson, reflection cost | Performance |
GOEXPERIMENT=jsonv2, encoding/json/v2 | The v2 experiment |
MaxBytesReader, depth, duplicate keys | Security |
encoding/xml tags, namespaces, Token | XML |
StdEncoding, URLEncoding, RawStdEncoding, padding | Base64 |
encoding/hex, encoding/gob, encoding/csv | Hex, gob and CSV |
| JSON Schema, Protobuf, MessagePack | Schemas and other formats |
| Every knob and every error text | Mechanics |
| Ready-made patterns | Solving the classic problems |
| Which package for which job | Choosing |
| Monolith to distributed system | In architecture |
| Reproduce the outputs | Lab |
| Wrong beliefs, cheat sheet, every term | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The packages.
| Package | In plain words | Streaming type | Gotcha |
|---|---|---|---|
encoding/json | Go value to and from JSON text | json.Encoder, json.Decoder | Numbers into any become float64 |
encoding/xml | Go value to and from XML | xml.Decoder.Token | xml.Name pins the root; namespaces are matched |
encoding/base64 | Bytes to printable text and back | base64.NewEncoder, NewDecoder | Four alphabets/padding variants that do not interoperate |
encoding/hex | Bytes to two hex digits each | hex.NewEncoder, hex.Dumper | Lower-case output; odd length is an error |
encoding/gob | Go-only binary self-describing format | gob.Encoder, gob.Decoder | Not for untrusted input, not for other languages |
encoding/csv | Records of string fields | csv.Reader, csv.Writer | Quotes, LazyQuotes, field-count check |
The struct tag options (encoding/json).
| Tag | Encoding effect | Decoding effect | Since |
|---|---|---|---|
json:"name" | Key is name | Key matched to field, case-insensitively | 1.0 |
json:"name,omitempty" | Dropped when false, 0, nil pointer/interface, empty array/slice/map/string | none | 1.0 |
json:"name,omitzero" | Dropped when the value is its type's zero value or IsZero() bool is true | none | 1.24 |
json:"name,string" | Number/bool/string written as a quoted JSON string | Expects a quoted value | 1.0 |
json:"-" | Field skipped | Field ignored | 1.0 |
json:"-," | Key is the literal - | Matches key - | 1.0 |
| no tag | Key is the Go field name | Same, case-insensitive | 1.0 |
| unexported field | Skipped silently | Skipped silently | 1.0 |
JSON to Go, through any.
| JSON | Go dynamic type | With UseNumber |
|---|---|---|
| object | map[string]any | same |
| array | []any | same |
| string | string | same |
| number | float64 | json.Number (a string) |
true/false | bool | same |
null | nil | same |
Base64 variants.
| Encoding | Alphabet 62/63 | Padding | Typical use |
|---|---|---|---|
StdEncoding | + / | yes (=) | MIME, JSON []byte, PEM bodies |
RawStdEncoding | + / | no | Compact binary in text without URLs |
URLEncoding | - _ | yes | URL-safe values with padding |
RawURLEncoding | - _ | no | JWT 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.
| Choice | Strength | Weakness |
|---|---|---|
Reflection-driven codec (encoding/json) | Zero generated code, tags next to fields | CPU and allocation cost, runtime errors for bad tags |
Generated codec (easyjson, Protobuf) | Fast, schema checked at build time | Build step, generated files |
Hand-written MarshalJSON | Total control, stable wire format | You own every edge case |
Decode into map[string]any | No struct needed | Lose 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
- "
omitemptydrops zero values." It drops only the fixed "empty" set (false, 0, nil, empty string/slice/map). A zerotime.Timeand a zero struct are never empty; that is why Go 1.24 addedomitzero. - "JSON numbers are integers or floats like in Go." The JSON text has digits; the receiver decides. Go's
anypicksfloat64; JavaScript only has doubles; anint64above 2^53 silently changes. - "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 errorReal 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 Unmarshal | Result | Exact error text |
|---|---|---|
{"age":"ten"} into int | UnmarshalTypeError, rest still decoded | json: cannot unmarshal string into Go struct field R.age of type int |
{"age":1.5} into int | UnmarshalTypeError | json: cannot unmarshal number 1.5 into Go struct field R.age of type int |
{"age":99999999999999999999} into int | overflow, UnmarshalTypeError | json: cannot unmarshal number 99999999999999999999 into Go struct field R.age of type int |
{"age":1 | SyntaxError | unexpected end of JSON input |
{"age":1}x | SyntaxError | invalid character 'x' after top-level value |
| non-pointer target | InvalidUnmarshalError | json: Unmarshal(non-pointer main.R) |
nil target | InvalidUnmarshalError | json: Unmarshal(nil) |
Marshal(math.NaN()) | UnsupportedValueError | json: unsupported value: NaN |
Marshal(make(chan int)) | UnsupportedTypeError | json: 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// 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 != "" }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 type | omitempty omits when | omitzero omits when |
|---|---|---|
bool | false | false |
int, float64 | 0 | 0 |
string | "" | "" |
*T, any | nil | nil |
[]T, map[K]V | length 0 (nil or empty) | nil only |
time.Time | never | IsZero() is true |
| struct | never | all fields zero (or IsZero() true) |
array [3]int | length 0 only | all 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 -> ignoredReal 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.
| Rule | Behaviour | Fix when it hurts |
|---|---|---|
| Case-insensitive match | {"NAME":"x"} fills name | encoding/json/v2 is case-sensitive; or validate keys yourself |
| Underscore/dash not folded | user_id is not userId | Add an exact tag or a custom UnmarshalJSON |
| Unexported ignored | silent | Export the field or use a DTO |
| Embedded struct flattened | fields appear at top level | Tag the embedded field to nest it: Audit `json:"audit"` |
| Name conflict, same depth, both tagged | both dropped | Rename 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// 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)
}Real output from the module's demo command:
float64: 9007199254740992
UseNumber: 9007199254740993Real 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 goes | Safe range | Fix beyond it |
|---|---|---|
Go int64 field | full 64-bit | none needed |
Go any | 2^53 (about 9.007e15) | UseNumber or a typed struct |
JavaScript JSON.parse | 2^53 | send as string, or use BigInt reviver |
PHP json_decode | int up to PHP_INT_MAX, then float | JSON_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 = 500Real 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() // ]// 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
}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).
| Method | Does | Error / result |
|---|---|---|
Decode(&v) | next value | io.EOF at clean end; io.ErrUnexpectedEOF inside a value |
Token() | next delimiter or scalar | json.Delim, string, float64, bool, nil |
More() | is there another element | bool |
DisallowUnknownFields() | unknown key is an error | json: unknown field "nmae" |
UseNumber() | numbers into any become json.Number | none |
Encode(v) | writes value and \n | write error |
SetEscapeHTML(false) | no < escapes | none |
SetIndent(p, i) | pretty-printed output | none |
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"// 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)
}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 type | Default JSON | Safer wire format |
|---|---|---|
time.Time | RFC 3339 string | same; use UTC; omitzero for optional |
time.Duration | integer nanoseconds | a string like "5s" via a wrapper, or integer milliseconds in the name (timeout_ms) |
iota enum | integer | text via TextMarshaler |
[]byte | Base64 (StdEncoding) string | same; document it |
map[int]T | keys become strings "1" | same |
float64 NaN/Inf | error | decide 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.
| Representation | nil/absent encodes as | Absent vs null on decode |
|---|---|---|
string | "" | cannot tell |
*string | null | cannot tell |
*string + omitempty | key omitted | cannot tell |
sql.NullString | {"String":"","Valid":false} | object, not null |
sql.Null[string] | {"V":"","Valid":false} | object, not null |
Optional[string] (snippet) | wrapper decides | can tell |
json.RawMessage | null for nil | can 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.
// 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| Error | Cause | Retry / client message |
|---|---|---|
*json.SyntaxError | invalid JSON text | 400 with the offset |
*json.UnmarshalTypeError | right JSON, wrong type | 422 naming the field and expected type |
*json.InvalidUnmarshalError | non-pointer or nil target | bug, panic in tests |
io.EOF (Decoder) | empty body | 400 "empty body" |
io.ErrUnexpectedEOF | cut-off body | 400 "truncated body" |
*http.MaxBytesError | body exceeds the limit | 413 |
json: unknown field "x" | DisallowUnknownFields | 400 naming the key |
*json.MarshalerError | a MarshalJSON failed | 500, 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.
| Technique | Gain | Cost |
|---|---|---|
Typed struct instead of map[string]any | fewer allocations, exact types | need a schema |
Encoder straight to http.ResponseWriter | no intermediate []byte | partial output on mid-stream error |
json.RawMessage for pass-through fields | skip decode/encode | validate separately |
easyjson (generated) | no reflection | generated files, tooling |
sonic, jsoniter | faster on benchmarks | dependency, subtle behaviour differences |
| Smaller payloads (omit empties, short keys) | less CPU and bytes | readability |
| Protobuf/MessagePack | smaller, faster | not 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)| Behaviour | v1 (encoding/json) | v2 (encoding/json/v2) |
|---|---|---|
| Key matching | case-insensitive | case-sensitive |
| Duplicate names | accepted, last wins | error |
omitempty | Go "empty" values | JSON empty values (null, "", {}, []) |
string option | string, bool, number, pointer | numbers only |
| Nil slice / map | null | [] / {} |
| Streaming API | Encoder/Decoder | MarshalWrite, UnmarshalRead, jsontext |
| Status | stable, frozen | experiment (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.
// 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| Risk | Where it bites | Defence |
|---|---|---|
| Unbounded body | memory exhaustion | MaxBytesReader, server ReadTimeout |
| Deep nesting | stack/CPU | built-in depth limit 10000, plus size limit |
| Mass assignment | extra fields bind to privileged struct fields | separate input DTO, DisallowUnknownFields |
| Duplicate keys | parser differentials between components | v2, or a validation pass; keep one parser per trust boundary |
| HTML in JSON embedded in a page | XSS | leave SetEscapeHTML(true); use html/template for pages |
| Large numbers | rounding of IDs | UseNumber, 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.
// 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.
| Tag | Meaning | Example |
|---|---|---|
xml:"id,attr" | attribute | id="A1" |
xml:",chardata" | element text | Widget |
xml:",innerxml" | raw inner bytes | children untouched |
xml:",comment" | comment | rush |
xml:"items>item" | nested path | wrapper element without a struct |
xml:",any" | any unmatched child | forward compatibility |
XMLName xml.Name | element and namespace | root 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.
// 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
}Real output for bytes FB FF FE 01:
+//+AQ== +//+AQ -__-AQ== -__-AQReal 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.
| Task | Use | Reason |
|---|---|---|
JSON []byte field | automatic StdEncoding | built in |
| Token inside a URL or filename | RawURLEncoding | no + / = to escape |
| MIME or PEM | StdEncoding (line breaks added separately) | RFC 2045/7468 expect padding |
| Read input from an unknown source | try Raw then Std, or trim = | padding is often stripped |
| Large file | NewEncoder and io.Copy | constant memory |
| Constant-time comparison | decode, then compare bytes | encodings 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| Package | Format | Cross-language | Use | Do not use for |
|---|---|---|---|---|
encoding/hex | text | yes | digests, ids, debugging | compact transport |
encoding/gob | binary | no (Go only) | Go-to-Go caches, test fixtures | untrusted input, public APIs |
encoding/csv | text | yes | exports, imports, spreadsheets | nested data |
encoding/json | text | yes | APIs, config | huge binary blobs |
encoding/xml | text | yes | legacy integrations, feeds | new 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
| Knob | Default | Effect | Where |
|---|---|---|---|
Decoder.DisallowUnknownFields() | off | unknown key becomes an error | json.Decoder |
Decoder.UseNumber() | off | numbers into any become json.Number | json.Decoder |
Encoder.SetEscapeHTML | true | escape <, >, & as < etc. | json.Encoder |
Encoder.SetIndent | none | pretty-printing | json.Encoder |
json.Valid(data) | n/a | syntax check, no decoding | encoding/json |
json.Indent, json.Compact, json.HTMLEscape | n/a | reformat existing bytes | encoding/json |
| Max nesting depth | 10000 | exceeded max depth | built in, not configurable |
http.MaxBytesReader | none | caps request body | net/http |
xml.Decoder.Strict | true | malformed XML is an error | xml.Decoder |
xml.Decoder.Entity | nil | custom entity map | xml.Decoder |
csv.Reader.LazyQuotes | false | accept bare quotes | csv.Reader |
csv.Reader.FieldsPerRecord | 0 | first record fixes width | csv.Reader |
base64.Encoding.Strict() | off | reject non-zero padding bits | encoding/base64 |
GOEXPERIMENT=jsonv2 | off | enable v2 packages and new backend (1.25+) | build time |
Error texts decoded Must-know
| Message | Source | Meaning |
|---|---|---|
unexpected end of JSON input | SyntaxError from Unmarshal | truncated or empty text |
invalid character '}' looking for beginning of object key string | SyntaxError | trailing comma |
invalid character 'x' after top-level value | SyntaxError | trailing data |
json: cannot unmarshal string into Go struct field R.age of type int | UnmarshalTypeError | wrong type |
json: unknown field "nmae" | Decoder | typo or extra key |
json: Unmarshal(non-pointer main.R) | InvalidUnmarshalError | forgot & |
json: unsupported type: chan int | UnsupportedTypeError | field has no JSON form |
json: unsupported value: NaN | UnsupportedValueError | NaN or Inf |
json: error calling MarshalJSON for type X: ... | MarshalerError | your method failed |
exceeded max depth | SyntaxError | more than 10000 nested levels |
http: request body too large | *http.MaxBytesError | limit hit |
XML syntax error on line 1: element <b> closed by </a> | xml.SyntaxError | mismatched tag |
illegal base64 data at input byte 6 | base64.CorruptInputError | wrong alphabet or padding |
encoding/hex: odd length hex string | hex | missing 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) -> 100Solving 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).
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
| Symptom | Likely cause | Check |
|---|---|---|
| Field always zero after decode | unexported, wrong tag, or underscore/dash mismatch | export it, compare key spelling |
0 missing from output | omitempty on a number | use *int or custom type |
"0001-01-01T00:00:00Z" in output | zero time.Time with omitempty | omitzero or *time.Time |
| Big id off by a few units | decoded into any | UseNumber or typed struct |
{"String":"","Valid":false} in API | returned sql.NullString | map to a DTO with *string |
null where [] expected | nil slice | initialise with make([]T, 0) |
< in output | HTML escaping | SetEscapeHTML(false) if safe |
| Memory spike on upload | no size cap | MaxBytesReader |
cannot unmarshal object into Go value of type string | schema drift | log the field path from UnmarshalTypeError.Field |
illegal base64 data | URL alphabet or missing padding | pick the matching Encoding |
Choosing
| Need | Pick | Reason |
|---|---|---|
| Public HTTP API payloads | encoding/json with typed DTOs | universal, tooling |
| Unknown or dynamic JSON | map[string]any with UseNumber, or RawMessage | keep digits and defer decoding |
| Huge arrays or NDJSON | Decoder with Token/More | constant memory |
| Hot path, millions per second | generated codec or Protobuf | no reflection |
| Strict contract, no extras | DisallowUnknownFields or v2 | reject typos |
| Legacy partner, SOAP, feeds | encoding/xml | the format they speak |
| Binary in a URL or token | RawURLEncoding | no escaping |
| Binary in JSON | []byte (Base64) | automatic |
| Go-to-Go cache entries | encoding/gob or MessagePack | compact, trusted |
| Spreadsheet export | encoding/csv | RFC 4180 style quoting |
| Cross-language, versioned | Protobuf, Avro, see Serialization Formats | schema 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 fieldsDistributed 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×
| Load | Concern | Action |
|---|---|---|
| 1× | Correctness | typed DTOs, size cap, error classification |
| 10× | Allocations show in profiles | reuse buffers, avoid map[string]any, stream exports |
| 100× | Codec CPU dominates | generated codecs or Protobuf for internal hops, test GOEXPERIMENT=jsonv2 on your benchmark, compress responses |
-- 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:
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
| PHP | Go | Note |
|---|---|---|
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]any | PHP integers stay int; Go any gives float64 |
JSON_THROW_ON_ERROR | always check err | without the flag PHP returns null on failure and you need json_last_error() |
JSON_BIGINT_AS_STRING | UseNumber | keep large integers exact |
JSON_UNESCAPED_SLASHES, JSON_HEX_TAG | SetEscapeHTML(false) | Go escapes <, >, & by default; PHP does not |
JSON_PRETTY_PRINT | SetIndent / MarshalIndent | |
JsonSerializable::jsonSerialize() | MarshalJSON() | PHP returns data to encode; Go returns the final bytes |
API Resource / toArray() | a DTO struct with tags | same role |
base64_encode, base64_decode($s, true) | StdEncoding | PHP strict mode ~ Go's strictness; URL variant needs strtr in PHP |
simplexml_load_string | xml.Unmarshal | libxml external-entity loading is off by default in current 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).
- 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- 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- Change
omitzerotoomitemptyonJoinedintags.goand rungo test ./tags. TheTestOmitzeroTimetest still passes, but encode a zeroUserand you will see"joined":"0001-01-01T00:00:00Z". - 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; thetagspackage passed under the experiment on this machine. - Serve
safebodyfrom a handler andcurl -da 2 MB body against a 1 MB cap. Expected, not run: HTTP 413 from your handler mapping*http.MaxBytesError. - Compare
go test -benchofjson.Unmarshalinto a struct and intomap[string]anyon your own payload; expected, not run: the struct is several times faster with fewer allocations.
Common misconceptions
| Belief | Reality |
|---|---|
omitempty omits zero values | it omits a fixed "empty" set; zero time.Time and structs stay, use omitzero |
| Pointer fields tell null from absent | both are nil; use a type that records that UnmarshalJSON ran |
map[string]any keeps my numbers | they become float64; digits beyond 2^53 are lost |
| A decode error means nothing was written | type errors keep decoding; only syntax errors write nothing |
Decoder caps the body size | it buffers a whole value; use http.MaxBytesReader |
Decode rejects trailing garbage | it reads one value; check for io.EOF with Token() |
| Unknown JSON keys are an error | ignored unless DisallowUnknownFields |
| JSON keys are case-sensitive | v1 matches case-insensitively; v2 does not |
sql.NullString marshals to a string or null | it marshals to an object with String and Valid |
time.Duration marshals as "5s" | it marshals as integer nanoseconds |
| Base64 encrypts | it is reversible encoding; padding and alphabet differ per variant |
| Go's XML parser is open to XXE | it does not fetch external entities; limit size and depth anyway |
gob is a safe fast JSON replacement | Go-only and unsafe for untrusted input |
| A faster JSON library is always a drop-in | escaping, float output and duplicate-key handling differ |
Cheat sheet
| Topic | Remember |
|---|---|
| Pointer to Unmarshal | json.Unmarshal(data, &v), always a non-nil pointer |
| Tag syntax | json:"name,omitempty"; - skips; string quotes numbers |
| Zero time omit | omitzero (Go 1.24) or *time.Time |
Numbers in any | float64; use UseNumber above 2^53 |
| Unknown fields | dec.DisallowUnknownFields() |
| Body cap | http.MaxBytesReader(w, r.Body, n) |
| Trailing data | dec.Token() must return io.EOF |
| Stream arrays | Token, then for dec.More() { Decode }, then Token |
| Enum as text | MarshalText/UnmarshalText (pointer receiver for unmarshal) |
| Null versus absent | custom Optional[T] with UnmarshalJSON |
| Error classification | errors.As to *json.SyntaxError, *json.UnmarshalTypeError (has Offset) |
| HTML escaping | on by default; SetEscapeHTML(false) to turn off |
| Base64 in URLs | RawURLEncoding, no padding |
| XML attribute | xml:"id,attr"; text xml:",chardata" |
| v2 | GOEXPERIMENT=jsonv2, Go 1.25+ experiment, stricter |
| gob | Go-only, never for untrusted data |
| CSV quotes | LazyQuotes = true accepts a bare " |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
encoding/json | Standard library JSON codec |
| Marshal | Go value to bytes |
| Unmarshal | Bytes into a Go value (needs a pointer) |
| Struct tag | String after a field type, read by reflection |
json tag | json:"name,options" |
omitempty | Drop false, 0, nil, empty string/slice/map |
omitzero | Drop the zero value or IsZero() true (Go 1.24) |
string option | Quote a number as a JSON string |
json:"-" | Skip the field |
| Case-insensitive matching | v1 key lookup ignoring case |
| Unexported field | Lower-case field, invisible to the codec |
| Embedded struct | Anonymous field whose fields are flattened |
json.RawMessage | Undecoded JSON bytes |
json.Number | Number kept as text |
UseNumber | Decoder option producing json.Number |
float64 | Default Go type for JSON numbers in any |
map[string]any | Generic JSON object |
Encoder / Decoder | Stream codecs over io.Writer / io.Reader |
| Decode loop | Repeated Decode until io.EOF |
More | Is another element present |
DisallowUnknownFields | Unknown keys become errors |
SetEscapeHTML | Toggle < escaping |
SetIndent | Pretty-print |
MarshalJSON / UnmarshalJSON | Custom JSON methods |
TextMarshaler | MarshalText; string form and map keys |
| Enum JSON | Integer by default, text via TextMarshaler |
| Nullable | JSON null representable in Go |
| Pointer field | *T; nil encodes as null |
sql.NullString | Database nullable, no JSON methods |
SyntaxError | Invalid JSON text, has Offset |
UnmarshalTypeError | Wrong JSON type, has Offset and Field |
| Offset | Byte position of the error |
| Reflection cost | Runtime type inspection overhead |
jsoniter | Third-party JSON codec |
sonic | Third-party JIT/SIMD JSON codec |
easyjson | Code-generating JSON codec |
| json/v2 | encoding/json/v2, experiment in 1.25 |
GOEXPERIMENT=jsonv2 | Build-time switch for v2 |
MaxBytesReader | Limits an HTTP request body |
| Duplicate keys | Same name twice in one object |
encoding/xml | XML codec |
| xml tag | xml:"name,attr" style |
| attr | XML attribute option |
| chardata | XML element text option |
| innerxml | Raw inner XML option |
| Namespace | XML name qualifier (urn:...) |
xml.Name | Struct holding space and local name |
Decoder.Token | Pull one XML token |
| Entity expansion | Replacing &x;; Go does not fetch external ones |
encoding/base64 | RFC 4648 codec |
StdEncoding | + / with padding |
URLEncoding | - _ with padding |
RawStdEncoding | + / without padding |
| Padding | = characters completing the last group |
NewEncoder | Streaming Base64 writer; needs Close |
encoding/hex | Hex codec |
encoding/gob | Go-only binary codec |
encoding/csv | CSV reader/writer |
LazyQuotes | Accept a bare quote in unquoted fields |
| JSON Schema | Schema language for validating JSON |
json_encode | PHP encoder |
JSON_THROW_ON_ERROR | PHP flag to throw instead of returning null |
JsonSerializable | PHP interface for custom encoding |
References
- Standards: RFC 8259 JSON, RFC 4648 Base16/32/64
- Go blog and release notes: JSON and Go, A new experimental Go API for JSON, Go 1.24 release notes (omitzero), Go 1.25 release notes (jsonv2)
- Package docs (Go 1.27.4 text read locally with
go doc -all; pkg.go.dev refuses automated clients): encoding/json, encoding/xml, encoding/base64, encoding/hex, encoding/gob, encoding/csv, net/http MaxBytesReader, encoding/json/v2 - PHP: json_encode, JsonSerializable, JSON constants
- Siblings: Binary-to-Text Encoding, Serialization Formats, Structs, Methods, Embedding & Struct Tags, The io Package, time.Time and Formatting, net/http, gRPC & Protobuf in Go, database/sql & pgx, JWT Deep Dive, Message Design & Schema Evolution, Testing & Benchmarking, Errors, Wrapping, Panic, Recover & Defer, reflect: When and How, Interfaces, Type Assertions, Type Switches & any