【问题标题】:how to convert map[string]interface{} data to struct如何将 map[string]interface{} 数据转换为 struct
【发布时间】:2022-01-07 13:29:23
【问题描述】:

我不知道怎么问,所以我举个例子问。

我有一些这样的数据

{
..
    "velocityStatEntries":  {

    "8753":  {

        "estimated":  {"value":  23.0,"text":  "23.0"},

        "completed":  {"value":  27.0,"text":  "27.0"}
    },

    "8673":  {

        "estimated":  {"value":  54.5,"text":  "54.5"},

        "completed":  {"value":  58.5,"text":  "58.5"}
    },
    .
    .
    .

    }
..
}

我想声明一个类型,它将映射键作为它的“KEY”或我给定的任何属性。 不使用地图迭代可以吗?

预期输出:

{...
   "velocityStatEntries": {
   {
     "key": "8753",
     "estimated":  {"value":  54.5,"text":  "54.5"},
     "completed":  {"value":  58.5,"text":  "58.5"}
   },
   {
     "key": "8673",
     "estimated":  {"value":  54.5,"text":  "54.5"},
     "completed":  {"value":  58.5,"text":  "58.5"}
   },
  }
...
}

这就是我所做的

type VelocityStatEntry struct {
    Key string
    Estimated struct {
        Value float64 `json:"value"`
        Text  string  `json:"text"`
    } `json:"estimated"`
    Completed struct {
        Value float64 `json:"value"`
        Text  string  `json:"text"`
    } `json:"completed"`
}

type RapidChartResponse struct {
    ...
    VelocityStatEntries map[string]VelocityStatEntry `json:"velocityStatEntries"`
    ..
}

但它不起作用。我想将该字符串映射键带到 KEY 属性。

【问题讨论】:

    标签: json go struct types go-map


    【解决方案1】:

    如果数据来自 JSON,那么您应该跳过 map[string]interface{},而是使用由您想要的结构实现的 custom unmarshaler 来执行您想要的操作。也许通过使用map[string]json.RawMessage。但是map[string]interface{} 到 struct 的转换是一件很痛苦的事情,尽量避免。

    例如:

    type VelocityStatEntryList []*VelocityStatEntry
    
    func (ls *VelocityStatEntryList) UnmarshalJSON(data []byte) error {
        var m map[string]json.RawMessage
        if err := json.Unmarshal(data, &m); err != nil {
            return err
        }
        for k, v := range m {
            e := &VelocityStatEntry{Key: k}
            if err := json.Unmarshal([]byte(v), e); err != nil {
                return err
            }
            *ls = append(*ls, e)
        }
        return nil
    }
    

    https://go.dev/play/p/VcaW_BWXRVr

    【讨论】:

    • 感谢您的回答!
    猜你喜欢
    • 2015-01-14
    • 2021-05-26
    • 2022-07-06
    • 2021-08-09
    • 2018-12-20
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多