Is there a way to change structs field tag dynamicly?
key := "mykey"
// a struct definition like
MyStruct struct {
field `json:key` //or field `json:$key`
}
// I want the following output
{
"mykey": 5
}
Couldn't find anything in the documentation.
You can customise how a type is marshaled by implementing the json.Marshaler
interface. This overrides the default behaviour of introspecting the fields of structs.
For this particular example, you could do something like:
func (s MyStruct) MarshalJSON() ([]byte, error) {
data := map[string]interface{}{
key: s.field,
}
return json.Marshal(data)
}
Here I'm constructing a map[string]interface{}
value that represents what I want in the JSON output and passing it to json.Marshal
.
You can test out this example here: http://play.golang.org/p/oTmuNMz-0e
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With