Golang variable inside json field tag

Is there a way to dynamically change the tag of a structs field?

key := "mykey"

// a struct definition like
MyStruct struct {
    field `json:key` //or field `json:$key` 
}

// I want the following output
{
     "mykey": 5
}

Could not find anything in the documentation .

+4
source share
1 answer

You can configure how a type is marshaled by implementing an json.Marshalerinterface . This overrides the default behavior for introspecting structure fields.

In this specific example, you can do something like:

func (s MyStruct) MarshalJSON() ([]byte, error) {
    data := map[string]interface{}{
        key: s.field,
    }
    return json.Marshal(data)
}

Here I create a value map[string]interface{}that represents what I want in the JSON output, and pass it to json.Marshal.

You can check this example here: http://play.golang.org/p/oTmuNMz-0e

+4
source

Source: https://habr.com/ru/post/1599434/


All Articles