您好,我有 json 數據,我將其解組為machines 切片?,F在我正在尋找將每個hostname從 machinesslice struct 復制/附加到serviceStruct []hosts 。我嘗試了幾種方法,但努力迭代servicestruct 中的 []hosts 切片。只是想知道將值從一個切片結構復制到另一個結構內的另一個切片值的最佳方法是什么。package mainimport ( "encoding/json" "fmt")type Machine struct { hostname string Ip string Name string}type Host struct { HostName string `json:"host_name"` Vars Var `json:"vars"`}type Service struct { ServiceName string `json:"service_name"` Required bool `json:"required"` Hosts []Host `json:"hosts"` Vars Var `json:"vars"`}func main() { machineInfo := `[{"dns":"1.1.1.1.eu-south-1.compute.amazonaws.com","ip":"1.1.1.1","name":"Machine-1"},{"dns":"1.1.1.2.eu-south-1.compute.amazonaws.com","ip":"1.1.1.2","name":"Machine-2"}]` var machines []Machine var mService *Service //convert the json to byts slice and then json.Unmarshal([]byte(machineInfo), &machines) //Data is now add to the structs for i, _ := range machines { mService.Hosts = append(mService.Hosts, machines[i].hostname) } fmt.Printf("Machines : %v", mService) data, _ := json.Marshal(mService) fmt.Println(string(data))}
1 回答

絕地無雙
TA貢獻1946條經驗 獲得超4個贊
讓我們從頂部開始:
通過大寫導出主機名字段。JSON 解碼器忽略意外字段。另外,添加一個標簽,使字段與文檔匹配:
type Machine struct {
Hostname string `json:"name"`
Ip string
Name string
}
將 mServices 聲明為一個值以避免 nil 指針恐慌:
var mService Service
使用復合文字表達式創建主機以附加到切片:
mService.Hosts = append(mService.Hosts, Host{HostName: machines[i].Hostname})
https://go.dev/play/p/nTBVwM3l9Iw
- 1 回答
- 0 關注
- 133 瀏覽
添加回答
舉報
0/150
提交
取消