Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将DynamicViper或JSON键解组为go中struct字段的一部分_Go_Viper Go - Fatal编程技术网

如何将DynamicViper或JSON键解组为go中struct字段的一部分

如何将DynamicViper或JSON键解组为go中struct字段的一部分,go,viper-go,Go,Viper Go,当JSON不是“期望”格式时,我发现GOLANG中的封送和解封非常混乱。例如,在一个JSON配置文件(我正试图与Viper一起使用)中,我有一个如下所示的配置文件: { "things" :{ "123abc" :{ "key1": "anything", "key2" : "more" }, "456xyz" :{ "key1": "anything2", "key2" : "more2" }, "bl

当JSON不是“期望”格式时,我发现GOLANG中的封送和解封非常混乱。例如,在一个JSON配置文件(我正试图与Viper一起使用)中,我有一个如下所示的配置文件:

{
  "things" :{
    "123abc" :{
      "key1": "anything",
      "key2" : "more"
    },
    "456xyz" :{
      "key1": "anything2",
      "key2" : "more2"
    },
    "blah" :{
      "key1": "anything3",
      "key2" : "more3"
    }
  }
}
其中“事物”可以是另一个对象中的对象,向下n级 我有一个结构:

type Thing struct {
  Name string  `?????`
  Key1 string  `json:"key2"`
  Key2 string  `json:"key2"`
}
如何解组JSON,更具体地说是viper配置(使用viper.Get(“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 X
if 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
}
type Thing struct{
名称字符串`json:“-”`//