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.
Code
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
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.