I need this result of JSON marshal:
["a", "b", ["c", "d"], "e"]
How correctly to do this in Go?
I need this result of JSON marshal:
["a", "b", ["c", "d"], "e"]
How correctly to do this in Go?
The trick to creating a slice/array of mixed types is to use the empty interface type that go offers
inner := []string{"c", "d"}
all := []interface{}{"a", "b", inner, "e"}
And then just json.Marshal
the interface slice. This works because any and all values implement at least an empty interface. You can use the most bloated object as though it doesn't have any methods/receiver functions to call. That's why people sometimes refer to go's interface{}
type as being a "generic" type. A lot of abstract stuff that packages do use interface{}
arguments, and then reflection to work out what was actually passed. Just look at the source of the encoding/json package and see how it unmarshals values...
https://play.golang.org/p/96VVo2F1m7
Unmarshalling would work in pretty much the same way: you can unmarshal JSON strings into interface{}
variables. You may need to use type-assertions and/or reflection to be able to work with the data though. That's why it's probably best to create types...