将数据从一个 Struct 传递到另一个 Struct 并转换为 json

pass data from one Struct to another Struct and convert to json

您好,我有 json 数据,我将其解组到机器切片。现在我正在查看 copy/append 每个集群信息,主机名从机器切片结构到集群结构 []Cluster 并尝试在该结构中填充不同的值。

每条机器记录都有一个关联的 serviceName 。我正在寻找下面所需输出中的 out json 格式,其中 service_name 、必需、变量、值仅传递一次,即使它们在从机器传递时与每个 json 记录相关联切片。

当前代码:

https://go.dev/play/p/6zVRIaLIgdN

期望的输出:

{
  "cluster_name": "dev",
  "services": [
    {
      "service_name": "serviceA",
      "required" : true,
      "vars": {
        "common_vars": {
          "user": "custom-user",
          "group": "custom-group"
        }
      },
      "hosts": [
        {
          "host_name": "host1",
          "vars": {
            "common_vars" :{
              "id": 1
            }
          }
        },
        {
          "host_name": "host2",
          "vars": {
            "common_vars":{
              "id": 2
            }
          }
        }

      ]
},
{
"service_name": "serviceB",
"required" : false
 .....
}
      
}
]
}

当前输出: 其中 ServiceName 与每个机器名称重复,我希望它在切片中有一次 service_name 输出

  "cluster_name": "dev",
  "services": [
    {
      "service_name": "serviceA",
      "required": true,
      "hosts": [
        {
          "host_name": "Machine-1",
          "vars": {
            "common_vars": {
              "id": "1"
            },
            "custom_listeners": {}
          }
        }
      ],
      "vars": {
        "custom_listeners": {}
      }
    },
    {
      **"service_name": "serviceA"**,
      "required": true,
      "hosts": [
        {
          "host_name": "Machine-2",
          "vars": {
            "common_vars": {
              "id": "2"
            },
            "custom_listeners": {}
          }
        }
      ],
      "vars": {
        "custom_listeners": {}
      }
    }
  ]
}

您必须实施一些逻辑来合并具有相同名称的服务记录。
map[<ServiceName>]<Service> 可用于避免每次都遍历服务切片。

m := map[string]*Service{}
for i := range machines {
    s, found := m[machines[i].Servicename]
    if !found {
        s = &Service{ServiceName: machines[i].Servicename, Required: true}
        m[machines[i].Servicename] = s
    }
    s.Hosts = append(s.Hosts, Host{HostName: machines[i].Hostname, Vars: Var{CommonVars: map[string]interface{}{"id": machines[i].ID}}})
}
for _, s := range m {
    cService.Services = append(cService.Services, *s)
}