我如何将动态Viper或JSON键解组为Go中的struct字段的一部分
当JSON不是“期望”格式时,我发现GOLANG中的编组和拆组非常混乱。例如,在JSON配置文件(我正尝试与Viper一起使用)中,我有一个配置文件,看起来像:
{  "things" :{
    "123abc" :{
      "key1": "anything",
      "key2" : "more"
    },
    "456xyz" :{
      "key1": "anything2",
      "key2" : "more2"
    },
    "blah" :{
      "key1": "anything3",
      "key2" : "more3"
    }
  }
}
其中“事物”可能是另一个对象中的一个对象n向下移动,我有一个struct:
type Thing struct {  Name string  `?????`
  Key1 string  `json:"key2"`
  Key2 string  `json:"key2"`
}
我该如何解组JSON,更具体地说是解编viper配置(使用viper.Get(“ things”))来获得Things类似数组:
t:= Things{   Name: "123abc",
   Key1: "anything",
   Key2: "more",
}
我尤其不确定如何将密钥作为结构字段
回答:
将地图用于动态键:
type X struct {    Things map[string]Thing
}
type Thing struct {
    Key1 string
    Key2 string
}
像这样解组:
var x Xif err := json.Unmarshal(data, &x); err != nil {
    // handle error
}
操场上的例子
如果名称必须是该结构的成员,请编写一个循环以在解组后将其添加:
type Thing struct {    Name string `json:"-"` // <-- add the field
    Key1 string
    Key2 string
}
...
// Fix the name field after unmarshal
for k, t := range x.Things {
    t.Name = k
    x.Things[k] = t
}
操场上的例子
以上是 我如何将动态Viper或JSON键解组为Go中的struct字段的一部分 的全部内容, 来源链接: utcz.com/qa/402582.html



