Golang变量在JSON字段标签内部

huangapple go评论112阅读模式
英文:

Golang variable inside json field tag

问题

有没有办法动态地更改结构体字段的标签?

  1. key := "mykey"
  2. // 类似于以下结构体定义
  3. MyStruct struct {
  4. field `json:key` // 或者 field `json:$key`
  5. }
  6. // 我想要以下输出
  7. {
  8. "mykey": 5
  9. }

文档中没有找到相关内容。

英文:

Is there a way to change structs field tag dynamicly?

  1. key := "mykey"
  2. // a struct definition like
  3. MyStruct struct {
  4. field `json:key` //or field `json:$key`
  5. }
  6. // I want the following output
  7. {
  8. "mykey": 5
  9. }

Couldn't find anything in the documentation.

答案1

得分: 5

你可以通过实现json.Marshaler接口来自定义类型的编组方式。这将覆盖默认行为,不再自动检查结构体的字段。

对于这个特定的例子,你可以这样做:

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

在这里,我构建了一个map[string]interface{}值,表示我想要在JSON输出中的内容,并将其传递给json.Marshal函数。

你可以在这里测试这个例子:http://play.golang.org/p/oTmuNMz-0e

英文:

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:

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

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

huangapple
  • 本文由 发表于 2015年7月24日 11:27:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/31601699.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定