我如何将动态Viper或JSON键解组为Go中的struct字段的一部分 [英] How Do I Unmarshal Dynamic Viper or JSON keys as part of struct field in go

查看:81
本文介绍了我如何将动态Viper或JSON键解组为Go中的struct字段的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了编组&当JSON不是期望"格式时,在GOLANG中取消编组非常混乱.例如,在一个JSON配置文件(我正在尝试与Viper一起使用)中,我有一个配置文件,如下所示:

I find the marshaling & unMarshaling in GOLANG very confusing when JSON is not in "desired" format. For example, in a JSON config file (which I am trying to use with Viper) I have a config file that looks like :

{
  "things" :{
    "123abc" :{
      "key1": "anything",
      "key2" : "more"
    },
    "456xyz" :{
      "key1": "anything2",
      "key2" : "more2"
    },
    "blah" :{
      "key1": "anything3",
      "key2" : "more3"
    }
  }
}

其中事物"可能是另一个对象,它在n个层次下而且我有一个结构:

where "things" could be an object in another object n levels down and I have a struct :

type Thing struct {
  Name string  `?????`
  Key1 string  `json:"key2"`
  Key2 string  `json:"key2"`
}

我该如何解组JSON,更具体地说,是如何进行viper配置(使用viper.Get("things"))来获取 Things 的数组,例如:

How to I go about unMarshalling the JSON and more specifically viper config (using viper.Get("things") to get an array of Things like:

t:= Things{
   Name: "123abc",
   Key1: "anything",
   Key2: "more",
}

我尤其不确定如何将密钥作为结构字段

I am particularly unsure how to get the key as a struct field

推荐答案

为动态键使用映射:

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
}

游乐场示例

如果名称必须是该结构的成员,则编写一个循环以在解组后将其添加:

If the name must be a member of the struct, then write a loop to add it after unmarshal:

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字段的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆