假設(shè)我有這個結(jié)構(gòu)塊:type AllShipments struct { Shipments []struct { ShipmentID int `json:"shipmentId"` ShipmentDate time.Time `json:"shipmentDate"` ShipmentItems []struct { OrderItemID string `json:"orderItemId"` OrderID string `json:"orderId"` } `json:"shipmentItems"` Transport struct { TransportID int `json:"transportId"` } `json:"transport"` } `json:"shipments"`}我用:func main() { var t AllShipments ..... ..... body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal(err) } err = json.Unmarshal(body, &t) if err != nil { fmt.Println(string(body)) } prettyJSON, err := json.MarshalIndent(t, "", " ") if err != nil { log.Fatal("Failed to generate json", err) } fmt.Printf("%s\n", string(prettyJSON))例如,如何僅獲取 json 字段“shipmentDate”,我嘗試過,t.Shipments.ShipmentDate但沒有成功。t.Shipments確實過濾掉了第一個數(shù)組。那么最好的方法是什么?我知道我可以禁用其他 json 字段,"json:-"但這不是我想要的。只是訪問該領(lǐng)域的一種方式
1 回答

慕婉清6462132
TA貢獻1804條經(jīng)驗 獲得超2個贊
t.Shipments
是一個切片 - 因此要訪問它的任何元素,您必須傳遞索引 - 然后您可以訪問該元素的字段,例如
if len(t.Shipments) > 0 { fmt.Println(v.Shipments[0].ShipmentDate) }
或在切片范圍內(nèi):
for i, v := range t.Shipments { fmt.Println(i, v.ShipmentDate) }
- 1 回答
- 0 關(guān)注
- 167 瀏覽
添加回答
舉報
0/150
提交
取消