Decode JSON Into Anonymous Structs

Decode one-off payloads with inline anonymous structs and json tags, including nested check lists, without declaring named types for every shape.

GoData Fetching

Code

gosnippet
38 lines
package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	payload := `{"service":"billing","version":"2.4.1","replicas":3}`

	// 一次性载荷:匿名结构体(anonymous struct)+ 内联 tag,免建具名类型
	var info struct {
		Service  string `json:"service"`
		Version  string `json:"version"`
		Replicas int    `json:"replicas"`
	}
	if err := json.Unmarshal([]byte(payload), &info); err != nil {
		panic(err)
	}
	fmt.Printf("%s@%s replicas=%d\n", info.Service, info.Version, info.Replicas)

	// 嵌套数组同样就地声明
	var health struct {
		Status string `json:"status"`
		Checks []struct {
			Name string `json:"name"`
			OK   bool   `json:"ok"`
		} `json:"checks"`
	}
	healthJSON := `{"status":"degraded","checks":[{"name":"db","ok":true},{"name":"queue","ok":false}]}`
	if err := json.Unmarshal([]byte(healthJSON), &health); err != nil {
		panic(err)
	}
	fmt.Println("status:", health.Status)
	for _, c := range health.Checks {
		fmt.Printf("check %s ok=%v\n", c.Name, c.OK)
	}
}

Walkthrough

Decode JSON Into Anonymous Structs is built around the function main.

A single loop drives the file — for _, c := range health.Checks. Every err != nil branch (2 sites) calls panic(err) — the run stops at the first failure instead of continuing in a broken state.

Points of care

  • Failures abort via panic(err) — nothing is returned for the caller to check, and nothing in the snippet recovers.

Putting it to use

The demo output is labeled (status:, check), so the output doubles as a step-by-step trace of what the file did.

Core lines

for _, c := range health.Checks {
	fmt.Printf("check %s ok=%v\n", c.Name, c.OK)
}

Interactive Tools for This Topic

FAQ

Does the snippet panic on failure?
It stops. All 2 `if err != nil` branches ends in `panic(err)` — nothing continues past a failed call.
What does Decode JSON Into Anonymous Structs print when run?
Execute the whole file; each printed line is prefixed with a label like `status:`, `check`.