Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang variable inside json field tag

Tags:

go

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.

like image 837
Thellimist Avatar asked Jul 24 '15 03:07

Thellimist


1 Answers

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

like image 57
James Henstridge Avatar answered Sep 29 '22 18:09

James Henstridge