I have the following
type Book struct {
Name string
Pages int
}
type Library struct {
Books []Book
}
And from an api I get all the Books and transform them like this:
var books []Book
json.Unmarshal(response, &books)
But now I receive another list of Books
from another api, but they come with different properties, which is why I add a MetaData
property to differentiate them.
type Book struct {
Name string
Page int
Metadata MetaData
}
type MetaData struct {
Type string `json:"type"`
Price string `json:"price,omitempty"`
}
Then together both arrangements in one and return as json.
books = append(response.Books, response2.Books...)
And I add omitempty
so that when they don't come, don't show them in the json, this is working fine. However, every time I want to add a new field / property I have to modify my book api and the extra api that I mentioned above. I wanted to know if there is any possibility that a struct has multiple fields or accepts them rather and does not show them in case they do not apply. You must say that I cannot modify the answers for the same format, and that they are all providers and it is out of my reach. The idea is to gather amabs answers and deliver only one to the front.
If you want to be lazy about it: unmarshal them to an array of the generic type map[string]interface{} in stead of a Book-type.
var books []map[string]interface{}
err := json.Unmarshal(response, &books)
Ofcourse this makes it harder to access concrete book properties, but it's not impossible.