【问题标题】:Golang Attach Struct into a JSON RawMessageGolang 将结构附加到 JSON RawMessage 中
【发布时间】:2021-07-03 17:35:16
【问题描述】:

我已经定义了一个这样的结构:

type components struct {
    Value  string `json:"value"`
    ID string `json:"id"`
    Name string `json:"name"`
}

我有 for 循环遍历整个表,对于 component 列,我将其解组并传递值 ID,以执行转换函数并返回结果。

for i := range table{
    var component []*components
    if err := json.Unmarshal(table[i].Components, &component); err != nil {
        panic(err)
    }

    for _, v := range component {
        if _, ok := map[v.ID+"-"+v.Val]; ok {
            val2,ID2,err:= transformation(v.ID, v.Val) 
            if err != nil{
                log.Fatal(errors.Wrap(err,"unrolling raw metric and raw machine error"))
            }
            v.Val = val2
            v.Name = val2
            v.ID = ID2
            }
        }
    }
}

调用转换函数后,它会返回一些预期值。我需要将所有返回值附加到组件上,而不是仅仅替换值。比如:

for i := range table{
    var component []*components
    if err := json.Unmarshal(table[i].Components, &component); err != nil {
        panic(err)
    }

for _, v := range component {
    if _, ok := map[v.ID+"-"+v.Val]; ok {
        res,err:= transformation(v.ID, v.Val) 

        //res is a component struct slice like ***var res []components*** and it contains multiple items

        if err != nil{
            log.Fatal(errors.Wrap(err,"unrolling raw metric and raw machine error"))
        }

        for i,s := range res{
            if i == 0{
                v.Val = s.Value
                v.Name = s.Name
                v.ID = s.ID
            }else{
                I would like to create a item for the component like {Name:s.Name,ID:s.ID,Val:v.Val} and attach to the component so I can have multiple items in the component
                }
            }

        }
    }
}

}

如果你能帮助我处理else 子句。基本上是将结构附加到 json 原始消息,如标题所示。

【问题讨论】:

    标签: json go struct slice


    【解决方案1】:

    在 else 中只是追加:

    component = append (component,&components_str{Val:s.Value,ID:s.UUID,Name:s.Name})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-24
      • 2023-02-11
      • 2021-11-24
      • 2014-04-06
      • 2016-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多