Golang 可变字段

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

Golang Changeable field

问题

我想知道是否可以为Go语言创建一个可变的结构体。以下是要翻译的内容:

这是一个问题。有不同的JSON对象。它始终包含"meta",但"data"会像下面这样变化。

  1. {"meta":{"A":"AA", "B":"BB"}, "data":{"C":"CC"}}
  2. {"meta":{"A":"DD", "B":"EE"}, "data":{"F":"FF"}}

在我的Go语言代码中,有很多用于JSON的结构体,如下所示。

  1. type meta struct {
  2. A string `json:"A"`
  3. B float64 `json:"B"`
  4. }
  5. type data1 struct {
  6. C int64 `json:"C"`
  7. }
  8. type JSON1 struct {
  9. MetaData meta `json:"meta"`
  10. Contents data1 `json:"data"`
  11. }
  12. type data2 struct {
  13. C int64 `json:"F"`
  14. }
  15. type JSON2 struct {
  16. MetaData meta `json:"meta"`
  17. Contents data2 `json:"data"`
  18. }

因此,我需要定义所有这些结构体。是否有任何方法可以使"Contents"字段可变,以减少对JSON "A"、"B"的定义?

提前感谢您的回复。

英文:

I'd like to know that is possible to make a changeable struct for golang.
Here is the thing.
there are the different objects of JSON.
It contains "meta" always, but "data" will be changed like below.

  1. {"meta":{"A":"AA, "B":"BB"}, "data":{"C":"CC"}}
  2. {"meta":{"A":"DD, "B":"EE"}, "data":{"F":"FF"}}

In my golang code, there is so many structs for JSON like below.

  1. type meta struct {
  2. A string `json:"A"`
  3. B float64 `json:"B"`
  4. }
  5. type data1 struct {
  6. C int64 `json:"C"`
  7. }
  8. type JSON1 struct {
  9. MetaData meta `json:"meta"`
  10. Contents data1 `json:"data"`
  11. }
  12. type data2 struct {
  13. C int64 `json:"F"`
  14. }
  15. type JSON2 struct {
  16. MetaData meta `json:"meta"`
  17. Contents data2 `json:"data"`
  18. }

So, I need to define all the struct.
Is there any way to make the Contents field is changeable to reduce JSON"A", "B" definitions?

Thanks for the reply in advance.

答案1

得分: 0

你可以使用map[string]interface{}类型。

  1. type JSON struct {
  2. MetaData meta `json:"meta"`
  3. Contents map[string]interface{} `json:"data"`
  4. }

然后可以像这样访问数据:

  1. var d JSON
  2. ...
  3. content, ok := d.Contents["F"] // 如果"F"不存在,ok的值为false
英文:

You can use map[string]interface{}

  1. type JSON struct {
  2. MetaData meta `json:"meta"`
  3. Contents map[string]interface{} `json:"data"`
  4. }

and then access data like:

  1. var d JSON
  2. ...
  3. content, ok := d.Contents["F"] // ok is false if "F" is not present

huangapple
  • 本文由 发表于 2021年10月21日 17:58:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/69659846.html
匿名

发表评论

匿名网友

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

确定