我正在開發一個項目,這是我第一次使用Go。在Go中創建結構以從API中讀取
該項目查詢了大量的API,並在大多數情況下,我沒有得到這個工作的麻煩。
從PHP背景來看,爲我的JSON響應創建Go類型定義有點不同。
我被困在一個API,Magento的API,它返回像這樣的JSON響應:
{
"66937": {
"entity_id": "66937",
"website_id": "1",
"email": "[email protected]",
"group_id": "1",
"created_at": "2017-08-11 02:09:18",
"disable_auto_group_change": "0",
"firstname": "Joe",
"lastname": "Bloggs",
"created_in": "New Zealand Store View"
},
"66938": {
"entity_id": "66938",
"website_id": "1",
"email": "[email protected]",
"group_id": "1",
"created_at": "2017-08-11 02:16:41",
"disable_auto_group_change": "0",
"firstname": "Jane",
"lastname": "Doe",
"created_in": "New Zealand Store View"
}
}
我一直在使用的工具,JSON-to-Go,幫我創造struct
類型,但是它不「T看起來很適合這種風格的響應:
type AutoGenerated struct {
Num0 struct {
EntityID string `json:"entity_id"`
WebsiteID string `json:"website_id"`
Email string `json:"email"`
GroupID string `json:"group_id"`
CreatedAt string `json:"created_at"`
DisableAutoGroupChange string `json:"disable_auto_group_change"`
Firstname string `json:"firstname"`
Lastname string `json:"lastname"`
CreatedIn string `json:"created_in"`
} `json:"0"`
Num1 struct {
EntityID string `json:"entity_id"`
WebsiteID string `json:"website_id"`
Email string `json:"email"`
GroupID string `json:"group_id"`
CreatedAt string `json:"created_at"`
DisableAutoGroupChange string `json:"disable_auto_group_change"`
Firstname string `json:"firstname"`
Lastname string `json:"lastname"`
CreatedIn string `json:"created_in"`
} `json:"1"`
}
所有我感興趣的是內JSON - 東西實際上與客戶做。我正在循環這個來提取一些信息。
如何創建所需的struct
以讀取此?
我看過任何數量的文檔或文章,但他們傾向於使用更簡單的JSON響應作爲示例。
@詹姆斯加入了答案循環細節。請看一看。 – jeevatkm