【问题标题】:How Do I Unmarshal Dynamic Viper or JSON keys as part of struct field in go我如何将动态 Viper 或 JSON 键解组为 go 中结构字段的一部分
【发布时间】:2018-06-08 04:52:24
【问题描述】:

当 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") 来获取 Things 的数组,例如:

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

我特别不确定如何将密钥作为结构字段获取

【问题讨论】:

    标签: go viper-go


    【解决方案1】:

    为动态键使用映射:

    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
    }
    

    Playground Example

    如果名字必须是struct的成员,那么在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
    }
    

    Playground example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-10
      • 2020-05-23
      • 2021-10-13
      • 2015-02-14
      • 1970-01-01
      • 2020-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多