Unmarshaling a JSON array into a Go struct

Sometimes, you see heterogeneous JSON array like

["Hello world", 10, false]

Dealing with such an array in Go can be very frustrating. A []interface{} hell is just about as painful as the map[string]interface{} hell (See my earlier article about that ).

The natural way to deal with data like that in Go would be a struct like

type Notification struct {
	Message  string
	Priority uint8
	Critical bool

See how much more meaning we've added?

Now, you can't just json.Unmarshal an array into a struct. I'll show you how to make that work.


2020-01-21T20:49:33-07:00, originally published 2016-01-13T13:22:06-08:00