Golang将结构附加到JSON消息中
我定义了这样一个结构:Golang将结构附加到JSON消息中,json,go,struct,slice,Json,Go,Struct,Slice,我定义了这样一个结构: type components struct { Value string `json:"value"` ID string `json:"id"` Name string `json:"name"` } 我让for循环遍历整个表,对于组件列,我将其解组并传递值ID,以执行转换函数并返回结果 for i := range table{ var component []*comp
type components struct {
Value string `json:"value"`
ID string `json:"id"`
Name string `json:"name"`
}
我让for循环遍历整个表,对于组件
列,我将其解组并传递值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
}
}
}
}
调用转换函数后,它将返回一些预期值。我需要将所有return val附加到组件,而不是仅仅替换该值。比如:
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
}
}
}
}
}
}
如果您能帮助我处理
其他
条款。基本上是将结构附加到json原始消息,如标题所示。中的else just append:
component = append (component,&components_str{Val:s.Value,ID:s.UUID,Name:s.Name})