Suppose I've written the following code snippet. Full code on the playground here for those inclined.
type Book struct {
Title string
Author string
}
func main() {
ms := Book{"Catch-22", "Joseph Heller"}
out, err := json.MarshalIndent(ms, "", " ")
if err != nil {
log.Fatalln(err)
}
fmt.Println(string(out))
}
This code outputs the following, exactly as I'd expect:
{
"Title": "Catch-22",
"Author": "Joseph Heller"
}
Suppose for a moment I wanted to add a field to the JSON output without including it in the Book
struct. Perhaps a genre:
{
"Title": "Catch-22",
"Author": "Joseph Heller",
"Genre": "Satire"
}
Can I use MarshalJSON()
to add an arbitrary field to the JSON payload on Marshal()
? Something like:
func (b *Book) MarshalJSON() ([]byte, error) {
// some code
}
Other answers make me think this should be possible, but I'm struggling to figure out the implementation.