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.

GoData Integrity

Code

gosnippet
28 lines
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

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.