英文:
How to model a Go struct after a JSON that has object values with arbitrary keys?
问题
我正在使用我的Go程序向API发出HTTP请求。请求体是一个JSON对象,如下所示:
{
"data": {
"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX": {
"status": "ok",
"message": "aaa",
"details": "bbb"
},
"ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ": {
"status": "ok",
"message": "ccc",
"details": "ddd"
}
}
}
其中"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
是一个任意的键。
如何定义一个结构体,使得该部分可以接受一个字符串值?以下是我的结构体,我知道它不能正确解码JSON:
type ReceiptResult struct {
Data ReceiptIDS `json:"data"`
}
type ReceiptIDS struct {
ReceiptID struct {
Status string `json:"status,omitempty"`
Message string `json:"message,omitempty"`
Details string `json:"details,omitempty"`
}
}
英文:
I am making an http request to an API from my go program. The request body is a JSON object as below:
{
"data": {
"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX": {
"status": "ok","message":"aaa","details":"bbb"
},
"ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ": {
"status": "ok","message":"ccc","details":"ddd"
}
}
}
Where "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
is an arbitrary key itself.
How to define a struct that allows that part to take a string value? Below is my struct, which I know does not allow me to properly decode the JSON:
type ReceiptResult struct {
Data ReceiptIDS `json:"data"`
}
type ReceiptIDS struct {
ReceiptID struct {
Status string `json:"status,omitempty"`
Message string `json:"message,omitempty"`
Details string `json:"details,omitempty"`
}
}
答案1
得分: 2
我看到问题了,你的结构体的结构是不必要的。
结构体应该像这样:
type ReceiptResult struct {
Data map[string]ReceiptIDS `json:"data"`
}
type ReceiptIDS struct {
Status string `json:"status,omitempty"`
Message string `json:"message,omitempty"`
Details string `json:"details,omitempty"`
}
Playground 上的工作示例:https://play.golang.org/p/EbJ2FhQOLz1
英文:
I see the problem here your struct's struct is unneeded.
Structs should look like this
type ReceiptResult struct {
Data map[string]ReceiptIDS `json:"data"`
}
type ReceiptIDS struct {
Status string `json:"status,omitempty"`
Message string `json:"message,omitempty"`
Details string `json:"details,omitempty"`
}
Playground working example: https://play.golang.org/p/EbJ2FhQOLz1
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论