akavel's digital garden

Go pattern: loose

I once found a neat (in my opinion) way to make it easier to write (and arguably still read easily) one-off JSON payloads. Part of the trick is to introduce a small local helper type (for which I hadn’t found a better name yet):

type loose map[string]any
json.NewEncoder(os.Stdout).Encode(loose{
	"foo": "go1.18+",
	"fee": loose{
		"fum": "baz",
	},
})

▶ Run

Update (2023): Replaced interface{} with any, available since Go ~1.18.

🌳 ripe — contents of this article got classified among complete works that I have edited and published as a cohesive whole. They are similar to a traditional blog post published at a point in time in that way—though I still tend these over time.
© Mateusz Czapliński 🐘 Mastodon 🐙 GitHub 🎮 Itch.io ♟️ BGG 🧶 Ravelry