=
package main import ( "fmt" "encoding/json" ) type Inner struct { Start int `json:"start"` End int `json:"end"` Status int `json:"status"` } type TwoMinute struct { Name string `json:"name"` Data []Inner `json:"data"` Label string `json:"label"` } func main() { inner1 := Inner{ Start:1, End:2, Status:3, } inner2 := Inner{ Start:11, End:22, Status:33, } var sl []Inner sl = append(sl, inner1, inner2) two := TwoMinute{ Name:"pd11", Label:"1#", Data:sl, } fmt.Println(two) var datas []TwoMinute datas = append(datas, two) inner3 := Inner{ Status:55, Start:66, End:77, } for i, _ := range datas { temp := datas[i].Data temp = append(temp, inner3) datas[i].Data = temp } js1, _ := json.MarshalIndent(datas, "", " ") fmt.Printf("%s ", js1) }
==
package main import ( "fmt" "encoding/json" "reflect" ) type sliceData []map[string]int type TwoMinute struct { Name string `json:"name"` Data sliceData `json:"data"` Label string `json:"label"` } func main() { m1 := map[string]int{ "start":1, "end":2, "status":3, } m2 := map[string]int{ "start":11, "end":22, "status":33, } var sl sliceData sl = append(sl, m1, m2) two := TwoMinute{ Name:"pd11", Label:"1#", Data:sl, } fmt.Println(two) var datas []TwoMinute datas = append(datas, two) m3 := map[string]int{ "start":44, "end":55, "status":66, } for i, obj := range datas { fmt.Println(obj.Data) rr := obj.Data fmt.Println(">>",reflect.TypeOf(rr), rr) obj.Data = append(obj.Data, m3) rr = append(rr, m3) fmt.Println("<<>>", rr) datas[i].Data = rr } js1, _ := json.MarshalIndent(datas, "", " ") fmt.Printf("%s ", js1) }
==指针:
package main import ( "fmt" "encoding/json" ) type Inner struct { Start int `json:"start"` End int `json:"end"` Status int `json:"status"` } type Sl []Inner type TwoMinute struct { Name string `json:"name"` Data *Sl `json:"data"` Label string `json:"label"` } func main() { inner1 := Inner{ Start:1, End:2, Status:3, } inner2 := Inner{ Start:11, End:22, Status:33, } var sl Sl sl = append(sl, inner1, inner2) two := TwoMinute{ Name:"pd11", Label:"1#", Data:&sl, } fmt.Println(two) var datas []TwoMinute datas = append(datas, two) inner3 := Inner{ Status:55, Start:66, End:77, } for _, obj := range datas { *obj.Data = append(*obj.Data,inner3) } js1, _ := json.MarshalIndent(datas, "", " ") fmt.Printf("%s ", js1) }