Say I want to be able to handle both nested and unnested json
s of the following form, as in this example:
source_json_1 := `{"owner": "John", "nickname": "Rose", "species": "Dog"}`
source_json_2 := `{"owner": "Doe", "Pet": [{"nickname": "Rose", "species": "Dog"},
{"nickname": "Max", "species": "Cat"}]}`
If I define Pet
as an embedded struct I can easily unmarshal it with:
type Owner struct {
Name string
Pet
}
type Pet struct {
NickName string
Species string
}
Resulting in John's pet getting adequately marshalled.
{John {Rose Dog}}
{Doe { }}
But since Pet
can actually also be a slice of Pet
s, Doe's Pet
s are not correctly unmarshalled. If instead go with
type Owner struct {
Name string
Pet []Pet
}
Then Doe gets marshalled just fine.
{John []}
{Doe [{Rose Dog} {Max Cat}]}
How can I catch both cases?
I'd prefer to marshall it into a slice of Pet
s in the end, no matter what.