Decode A JSON Array Into Records
Unmarshal a JSON array straight into []struct with json tags, then print one formatted field per record to prove the shape.
Code
package main
import (
"encoding/json"
"fmt"
)
type Metric struct {
Service string `json:"service"`
Value float64 `json:"value"`
Healthy bool `json:"healthy"`
}
func main() {
payload := `[
{"service": "auth", "value": 12.5, "healthy": true},
{"service": "billing", "value": 48.0, "healthy": false}
]`
var metrics []Metric
if err := json.Unmarshal([]byte(payload), &metrics); err != nil {
fmt.Println("decode failed:", err)
return
}
for _, m := range metrics {
fmt.Printf("%s value=%.1f healthy=%v\n", m.Service, m.Value, m.Healthy)
}
}What the file does in order
All of the logic lives in the function main.
The loop for _, m := range metrics is the only repeated construct. Error handling is inline: 1 place test err != nil and branch immediately.
Caveats
- Nothing to install: the snippet stays inside the standard library.
Applying it
The entry-point signature is func main()
The file’s steps show up in the output as decode failed:.
Statements that matter
for _, m := range metrics {
fmt.Printf("%s value=%.1f healthy=%v\n", m.Service, m.Value, m.Healthy)
}
Interactive Tools for This Topic
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.Base45 Encoder and DecoderEncode and decode text with the Base45 alphabet defined in RFC 9285, with UTF-8 support, padding-free output, and clear validation errors.
FAQ
- What does Decode A JSON Array Into Records print when run?
- Invoke the file as-is — the `decode failed:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.