我正在开发一个项目,这是我第一次使用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