Home > database >  Convert a slice of interface to an io.Reader object in golang?
Convert a slice of interface to an io.Reader object in golang?

Time:10-23

I am trying to do this data conversion but I am stuck. I have this json request body:

{
    "city": "XYZ",
    "vouchers" :[
        {
            "voucherCode": "VOUCHERA",
            "amount": 1000
        },
        {
            "voucherCode": "VOUCHERB",
            "amount":23
        }
    ]
}

I want to get the vouchers json array and pass it as a request payload to another API. Currently I am doing this to get the vouchers array:

type vouchers struct {
    Vouchers []interface{} `json:"vouchers" form:"vouchers"`
}

vouchers := vouchers{}
json.Unmarshal(reqBody, &vouchers)

This gives me the vouchers object but how do I convert this to an io.Reader object and send it as a payload to another API?

CodePudding user response:

Figured out one way to solve it, thanks to some help on the Discord Gophers channel. vouchers json object can be unmarshalled into a field of type json.RawMessage, which then can be passed in bytes.NewReader.

type vouchers struct {
    Vouchers json.RawMessage `json:"vouchers" form:"vouchers"`
}

vouchers := vouchers{}
json.Unmarshal(reqBody, &vouchers)

This can be later passed as a payload to another API using bytes.NewReader(vouchers.Vouchers).

  • Related