I have a type MonthYear
defined like
type MonthYear time.Time
func (my *MonthYear) MarshalJSON() ([]byte, error) {
t := time.Time(*my)
return json.Marshal(&struct {
Month int `json:"month"`
Year int `json:"year"`
}{
Month: int(t.Month()) - 1,
Year: t.Year(),
})
}
I'm including it a lot of different structs like
type Event struct {
Name string `json:"name"`
Date MonthYear
}
type Item struct {
Category string `json:"category"`
Date MonthYear
}
How do I inline the MonthYear
type so that the resulting JSON does not have any embedded objects?
I want the result to look like { "name": "party", "month": 2, "year": 2017 }
and { "category": "art", "month": 3, "year": 2016 }
without having to write the MarshalJSON for each of the structs.
I know this is not the answer you wish to receive, but until inline support is added to the encoding/json
package, you may use the following workaround:
Make your MonthYear
a struct, e.g.:
type MonthYear struct {
t time.Time
Month int `json:"month"`
Year int `json:"year"`
}
An optional, constructor function for easy creation:
func NewMonthYear(t time.Time) MonthYear {
return MonthYear{
t: t,
Month: int(t.Month()) - 1,
Year: t.Year(),
}
}
And use embedding (anonymous field) instead of a regular (named) field to get "flattened" / inlined in the JSON representation:
type Event struct {
Name string `json:"name"`
MonthYear
}
type Item struct {
Category string `json:"category"`
MonthYear
}
As an extra, you'll be able to refer to fields directly like Event.Year
or Event.Month
which is nice.
Testing it:
evt := Event{Name: "party", MonthYear: NewMonthYear(time.Now())}
fmt.Println(json.NewEncoder(os.Stdout).Encode(evt), evt.Year)
itm := Item{Category: "Tool", MonthYear: NewMonthYear(time.Now())}
fmt.Println(json.NewEncoder(os.Stdout).Encode(itm))
Output (try it on the Go Playground):
{"name":"party","month":10,"year":2009}
<nil> 2009
{"category":"Tool","month":10,"year":2009}
<nil>
Note: The MonthYear.t
time field does not play a role here (it is not marshaled either). You can remove it if the original time.Time
is not needed.