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

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

How to model a Go struct after a JSON that has object values with arbitrary keys?

问题

我正在使用我的Go程序向API发出HTTP请求。请求体是一个JSON对象,如下所示:

  1. {
  2. "data": {
  3. "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX": {
  4. "status": "ok",
  5. "message": "aaa",
  6. "details": "bbb"
  7. },
  8. "ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ": {
  9. "status": "ok",
  10. "message": "ccc",
  11. "details": "ddd"
  12. }
  13. }
  14. }

其中"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"是一个任意的键。

如何定义一个结构体,使得该部分可以接受一个字符串值?以下是我的结构体,我知道它不能正确解码JSON:

  1. type ReceiptResult struct {
  2. Data ReceiptIDS `json:"data"`
  3. }
  4. type ReceiptIDS struct {
  5. ReceiptID struct {
  6. Status string `json:"status,omitempty"`
  7. Message string `json:"message,omitempty"`
  8. Details string `json:"details,omitempty"`
  9. }
  10. }
英文:

I am making an http request to an API from my go program. The request body is a JSON object as below:

  1. {
  2. "data": {
  3. "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX": {
  4. "status": "ok","message":"aaa","details":"bbb"
  5. },
  6. "ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ": {
  7. "status": "ok","message":"ccc","details":"ddd"
  8. }
  9. }
  10. }

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:

  1. type ReceiptResult struct {
  2. Data ReceiptIDS `json:"data"`
  3. }
  4. type ReceiptIDS struct {
  5. ReceiptID struct {
  6. Status string `json:"status,omitempty"`
  7. Message string `json:"message,omitempty"`
  8. Details string `json:"details,omitempty"`
  9. }
  10. }

答案1

得分: 2

我看到问题了,你的结构体的结构是不必要的。

结构体应该像这样:

  1. type ReceiptResult struct {
  2. Data map[string]ReceiptIDS `json:"data"`
  3. }
  4. type ReceiptIDS struct {
  5. Status string `json:"status,omitempty"`
  6. Message string `json:"message,omitempty"`
  7. Details string `json:"details,omitempty"`
  8. }

Playground 上的工作示例:https://play.golang.org/p/EbJ2FhQOLz1

英文:

I see the problem here your struct's struct is unneeded.

Structs should look like this

  1. type ReceiptResult struct {
  2. Data map[string]ReceiptIDS `json:"data"`
  3. }
  4. type ReceiptIDS struct {
  5. Status string `json:"status,omitempty"`
  6. Message string `json:"message,omitempty"`
  7. Details string `json:"details,omitempty"`
  8. }

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:

确定