Home > other >  How to create a go struct from a JSON object that has a string value in place of a tag? [closed]
How to create a go struct from a JSON object that has a string value in place of a tag? [closed]

Time:09-24

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 not a tag rather a string value. How to have a struct that allow that part to take a string value. Below is my struct , which i know does not allow me to decode the JSON to the struct:

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"`
    }
}

CodePudding user response:

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

  • Related