這是我定義的結構 - 從 json to Go struct 工具生成:
type NYTimesNews struct {
Data struct {
LegacyCollection struct {
CollectionsPage struct {
Stream struct {
Edges []struct {
Node struct {
FirstPublished string `json:"firstPublished"`
Headline struct {
Default string `json:"default"`
} `json:"headline"`
Summary string `json:"summary"`
URL string `json:"url"`
} `json:"node"`
} `json:"edges"`
} `json:"stream"`
} `json:"collectionsPage"`
} `json:"legacyCollection"`
} `json:"data"`
}
當我在節點層迭代我的請求的回應時,一切正常并且可以列印出來,下面是列印出 Edges 陣列中所有節點的代碼
for i, Node:= range data.Data.LegacyCollection.CollectionsPage.Stream.Edges{
// fmt.Printf("[%d] \n %s \n", i, Node)
fmt.Printf("[%d] \n %s \n %s\n", i, reflect.TypeOf(Node),Node)
}
輸出
[0]
struct { Node struct { FirstPublished string "json:\"firstPublished\""; Headline struct { Default string "json:\"default\"" } "json:\"headline\""; Summary string "json:\"summary\""; URL string "json:\"url\"" } "json:\"node\"" }
{{2022-05-14T21:17:13.000Z {Turkey Offers to Evacuate Mariupol Fighters Despite Disagreements} Turkey has had a ship waiting for weeks in Istanbul to evacuate those remaining in the Azovstal steel plant, but Ukraine and Russia have not agreed to a plan, a Turkish official said. https://www.nytimes.com/2022/05/14/world/europe/azovstal-evacuation-turkey.html}}
[1]
struct { Node struct { FirstPublished string "json:\"firstPublished\""; Headline struct { Default string "json:\"default\"" } "json:\"headline\""; Summary string "json:\"summary\""; URL string "json:\"url\"" } "json:\"node\"" }
{{2022-05-14T16:26:03.000Z {Catalan Pop? Corsican Rock? It’s Europe’s Other Song Contest.} The Liet International, a competition for minority and regional languages, lacks the glitz of Eurovision. But its organizers say it helps keep endangered tongues alive. https://www.nytimes.com/2022/05/14/arts/music/minority-languages-song-contest.html}}
但是當我嘗試訪問節點結構中的單個欄位時發生錯誤
修改后的代碼:
for i, Node:= range data.Data.LegacyCollection.CollectionsPage.Stream.Edges{
fmt.Printf("[%d] \n %s \n %s -------- \n\n", i, reflect.TypeOf(Node), Node.FirstPublished)
break
}
輸出
./getdata-url-nytimes.go:92:80: Node.FirstPublished undefined (type struct{Node struct{FirstPublished string "json:"firstPublished""; Headline struct{Default string "json:"default""} "json :"headline""; 摘要字串 "json:"summary""; URL 字串 "json:"url""} "json:"node""} 沒有欄位或方法 FirstPublished)
當我使用'doc fieldname'列印 Go 結構中的欄位時,有什么問題嗎?
uj5u.com熱心網友回復:
您命名Node了回圈變數,但它真正包含的是 type 的結構Edge。是您迭代的集合.Node中每個的屬性。Edge您需要.Node像這樣通過 edge 的欄位訪問它:
for i, edge:= range data.Data.LegacyCollection.CollectionsPage.Stream.Edges{
fmt.Printf("[%d] \n %s \n %s -------- \n\n", i, reflect.TypeOf(edge.Node), edge.Node.FirstPublished)
break
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/474690.html
上一篇:我還應該宣告GOPATH嗎?
