TExcelTAD
Home › Automation Scripting: Bash, Python & Go › encoding/json for Tools

encoding/json for Tools

Go tools spend much of their time turning JSON into structs and back: API responses, kubectl … -o json output, config files, machine-readable output for the next tool in a pipeline. encoding/json does it with struct tags. This lesson covers the parts that matter for tooling: decoding only what you need, optional fields, strictness about unknown fields, partially dynamic data, and streaming.

Decode only what you need

A struct describes the fields you care about; everything else in the document is ignored. Tags map JSON names to Go fields, and nested structs follow the document's shape:

go · try it yourself
package main

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

type PodList struct {
	Items []Pod `json:"items"`
}

type Pod struct {
	Metadata struct {
		Name   string            `json:"name"`
		Labels map[string]string `json:"labels"`
	} `json:"metadata"`
	Status struct {
		Phase             string `json:"phase"`
		ContainerStatuses []struct {
			Ready        bool `json:"ready"`
			RestartCount int  `json:"restartCount"`
		} `json:"containerStatuses"`
	} `json:"status"`
}

const data = `{"apiVersion": "v1", "kind": "List", "items": [
 {"metadata": {"name": "api-7d9f", "uid": "a1", "labels": {"app": "api"}},
  "status": {"phase": "Running", "hostIP": "10.0.0.4", "containerStatuses": [{"ready": true, "restartCount": 0}]}},
 {"metadata": {"name": "api-x2kq", "labels": {"app": "api"}},
  "status": {"phase": "Running", "containerStatuses": [{"ready": false, "restartCount": 7}]}},
 {"metadata": {"name": "migrate-q8z1"}, "status": {"phase": "Pending"}}]}`

func main() {
	var list PodList
	if err := json.Unmarshal([]byte(data), &list); err != nil {
		log.Fatal(err)
	}
	for _, p := range list.Items {
		restarts, ready := 0, len(p.Status.ContainerStatuses) > 0
		for _, c := range p.Status.ContainerStatuses {
			restarts += c.RestartCount
			ready = ready && c.Ready
		}
		app := p.Metadata.Labels["app"] // reading a nil map is fine: returns ""
		fmt.Printf("%-13s app=%-4q phase=%-8s ready=%-5v restarts=%d\n",
			p.Metadata.Name, app, p.Status.Phase, ready, restarts)
	}
}
api-7d9f      app="api" phase=Running  ready=true  restarts=0
api-x2kq      app="api" phase=Running  ready=false restarts=7
migrate-q8z1  app=""   phase=Pending  ready=false restarts=0
  • Fields missing from the document keep their zero value ("", 0, false, nil). The pending pod has no labels and no container statuses, and the code handles both without special cases.
  • Unexported (lower-case) fields are never decoded. A field with no tag matches its JSON name case-insensitively, but writing tags makes the mapping explicit.
  • Unknown fields (uid, hostIP, apiVersion) are ignored, so the tool keeps working when the API adds fields.

Missing vs zero: pointers and omitempty

Sometimes "absent" and "zero" mean different things: replicas: 0 (scale to zero) is not the same as "replicas not specified". A pointer field is nil when the key was absent. On output, omitempty leaves out empty values, and omitzero (Go 1.24+) leaves out zero values, including zero structs:

go · try it yourself
package main

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

type Patch struct {
	Replicas *int             `json:"replicas,omitempty"` // nil = do not change
	Image    string           `json:"image,omitempty"`
	Labels   map[string]string `json:"labels,omitempty"`
}

func describe(p Patch) string {
	if p.Replicas == nil {
		return "replicas: unchanged"
	}
	return fmt.Sprintf("replicas: set to %d", *p.Replicas)
}

func main() {
	for _, in := range []string{`{"image": "shop-api:1.5.0"}`, `{"replicas": 0}`, `{"replicas": 3}`} {
		var p Patch
		json.Unmarshal([]byte(in), &p)
		fmt.Printf("%-30s -> %s\n", in, describe(p))
	}

	zero := 0
	enc := json.NewEncoder(os.Stdout)
	enc.Encode(Patch{Image: "shop-api:1.5.0"})
	enc.Encode(Patch{Replicas: &zero})
	enc.SetIndent("", "  ")
	enc.Encode(Patch{Replicas: &zero, Labels: map[string]string{"tier": "api", "app": "shop"}})
}
{"image": "shop-api:1.5.0"}    -> replicas: unchanged
{"replicas": 0}                -> replicas: set to 0
{"replicas": 3}                -> replicas: set to 3
{"image":"shop-api:1.5.0"}
{"replicas":0}
{
  "replicas": 0,
  "labels": {
    "app": "shop",
    "tier": "api"
  }
}

json.Marshal sorts map keys, so encoded maps are deterministic even though Go's map iteration is not.

Strict decoding for config files

Ignoring unknown fields is right for API responses and wrong for config files, where an unknown key is almost always a typo. A json.Decoder with DisallowUnknownFields rejects them, and the error types say where the problem is:

go · try it yourself
package main

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

type Config struct {
	Service  string `json:"service"`
	Replicas int    `json:"replicas"`
	Timeout  string `json:"timeout"`
}

func load(text string) (Config, error) {
	var c Config
	dec := json.NewDecoder(strings.NewReader(text))
	dec.DisallowUnknownFields()
	if err := dec.Decode(&c); err != nil {
		var typeErr *json.UnmarshalTypeError
		var syntaxErr *json.SyntaxError
		switch {
		case errors.As(err, &typeErr):
			return c, fmt.Errorf("field %q: expected %s, got JSON %s", typeErr.Field, typeErr.Type, typeErr.Value)
		case errors.As(err, &syntaxErr):
			return c, fmt.Errorf("syntax error at byte %d: %v", syntaxErr.Offset, err)
		}
		return c, err
	}
	if c.Service == "" {
		return c, errors.New(`"service" is required`)
	}
	return c, nil
}

func main() {
	for _, text := range []string{
		`{"service": "shop-api", "replicas": 3, "timeout": "30s"}`,
		`{"service": "shop-api", "replicsa": 3}`,
		`{"service": "shop-api", "replicas": "3"}`,
		`{"service": "shop-api", "replicas": 3,}`,
		`{"replicas": 3}`,
	} {
		c, err := load(text)
		if err != nil {
			fmt.Println("error:", err)
			continue
		}
		fmt.Printf("ok: %+v\n", c)
	}
}
ok: {Service:shop-api Replicas:3 Timeout:30s}
error: json: unknown field "replicsa"
error: field "replicas": expected int, got JSON string
error: syntax error at byte 39: invalid character '}' looking for beginning of object key string
error: "service" is required

Partly dynamic data: RawMessage and map[string]any

Event streams and webhooks often have a type field that decides the shape of the rest. json.RawMessage keeps a part undecoded until you know which struct to use; map[string]any decodes anything (numbers become float64):

go · try it yourself
package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"strings"
)

type Envelope struct {
	Type string          `json:"type"`
	Data json.RawMessage `json:"data"`
}
type Deploy struct {
	Service string `json:"service"`
	Version string `json:"version"`
}
type Alert struct {
	Name     string `json:"name"`
	Severity string `json:"severity"`
}

const events = `{"type": "deploy", "data": {"service": "shop-api", "version": "1.5.0"}}
{"type": "alert", "data": {"name": "HighLatency", "severity": "page"}}
{"type": "audit", "data": {"user": "ada", "action": "login", "attempts": 2}}
`

func main() {
	sc := bufio.NewScanner(strings.NewReader(events)) // one JSON document per line (JSON Lines)
	for sc.Scan() {
		var env Envelope
		if err := json.Unmarshal(sc.Bytes(), &env); err != nil {
			fmt.Println("bad line:", err)
			continue
		}
		switch env.Type {
		case "deploy":
			var d Deploy
			json.Unmarshal(env.Data, &d)
			fmt.Printf("deploy: %s -> %s\n", d.Service, d.Version)
		case "alert":
			var a Alert
			json.Unmarshal(env.Data, &a)
			fmt.Printf("alert:  %s (%s)\n", a.Name, a.Severity)
		default:
			var m map[string]any
			json.Unmarshal(env.Data, &m)
			fmt.Printf("other:  %s %v (attempts is a %T)\n", env.Type, m, m["attempts"])
		}
	}
}
deploy: shop-api -> 1.5.0
alert:  HighLatency (page)
other:  audit map[action:login attempts:2 user:ada] (attempts is a float64)

bufio.Scanner reads JSON Lines one line at a time, so a multi-gigabyte log never sits in memory (its default line limit is 64 KiB; raise it with sc.Buffer for long lines). For one large JSON array, json.Decoder with Token() and More() streams elements the same way.

Note: Go 1.25 also ships an experimental encoding/json/v2 behind GOEXPERIMENT=jsonv2, with faster decoding and stricter defaults (for example, case-sensitive field matching). The v1 API above remains the stable choice.

Test yourself

What happens to JSON fields that have no matching struct field when decoding with json.Unmarshal?

  1. Unmarshal returns an error
  2. They are ignored
  3. They are stored in a hidden map
  4. The program panics

How can a tool tell "replicas": 0 apart from no replicas key at all?

  1. Check if the int is 0
  2. Declare the field as *int: it is nil when the key was absent
  3. Use omitempty
  4. It cannot

What Go type does map[string]any give a JSON number like 2?

  1. int
  2. int64
  3. float64
  4. string