William Poussier William Poussier - 4 months ago 85
JSON Question

Golang multiple json tag names for one field

It it possible in Golang to use more than one name for a JSON struct tag ?

type Animation struct {
Name string `json:"name"`
Repeat int `json:"repeat"`
Speed uint `json:"speed"`
Pattern Pattern `json:"pattern",json:"frames"`
}

Answer

It is not allowed to have more than one tag for a single field. In a case where would require such functionality you can use type Info map[string]string instead of your struct.

Or you can use both types in your structure, and make method Patterns() which will return right pattern.

type Animation struct {
    Name    string  `json:"name"`
    Repeat  int     `json:"repeat"`
    Speed   uint    `json:"speed"`
    Pattern Pattern `json:"pattern"`
    Frame   Pattenn `json:"frames"`
}

func (a Animation) Details() Pattern {
    if a.Pattern == nil {
        return a.Frame
    }
    return a.Pattern
}