如何在Go中对一个具有任意键的对象值的JSON进行建模?

huangapple go评论65阅读模式
英文:

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

huangapple
  • 本文由 发表于 2021年9月23日 23:38:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/69303044.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定