Flexible JSON Shapes Object Or Array
Accept payloads that arrive as an {"orders": [...]} envelope or a bare array by trying two Unmarshal targets in order and falling back cleanly.
Code
package main
import (
"encoding/json"
"fmt"
)
type Order struct {
ID string `json:"id"`
Total float64 `json:"total"`
}
// decodeOrders accepts either an {"orders": [...]} envelope or a bare array.
func decodeOrders(payload []byte) ([]Order, error) {
var envelope struct {
Orders []Order `json:"orders"`
}
if err := json.Unmarshal(payload, &envelope); err == nil && envelope.Orders != nil {
return envelope.Orders, nil
}
var list []Order
if err := json.Unmarshal(payload, &list); err != nil {
return nil, fmt.Errorf("payload is neither object envelope nor array: %w", err)
}
return list, nil
}
func main() {
cases := []struct {
name string
payload []byte
}{
{"envelope", []byte(`{"orders":[{"id":"o-1","total":42.5}]}`)},
{"bare array", []byte(`[{"id":"o-2","total":9.99}]`)},
}
for _, c := range cases {
orders, err := decodeOrders(c.payload)
if err != nil {
fmt.Println(c.name, "failed:", err)
continue
}
fmt.Printf("%s: %d orders, first id %s\n", c.name, len(orders), orders[0].ID)
}
}Reading the code — Flexible JSON Shapes Object Or Array
Everything happens inside the functions decodeOrders and main.
The loop for _, c := range cases is the only repeated construct. Every fallible call checks err != nil (2 sites), so an error is handled where it happens rather than bubbling invisibly.
Caveats
- The standard library is the entire toolkit here — nothing else needs setting up.
- Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Applying it
The entry-point signature is func decodeOrders(payload []byte) ([]Order, error)
Execute the file and main walks through decodeOrders, in that order.
Statements that matter
return nil, fmt.Errorf("payload is neither object envelope nor array: %w", err)
for _, c := range cases {
orders, err := decodeOrders(c.payload)
if err != nil {
fmt.Println(c.name, "failed:", err)
continue
}
fmt.Printf("%s: %d orders, first id %s\n", c.name, len(orders), orders[0].ID)
}
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?
- Through `error` values, not panics — the snippet checks `err != nil` at 2 sites.
- How do you run Flexible JSON Shapes Object Or Array?
- The file is self-contained: run it directly, no dependencies to install beforehand.
Report a problem with this exampleOpens a pre-filled issue on GitHub.