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.

GoData Integrity

Code

gosnippet
46 lines
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 err before 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

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.