How to properly scan postgresql JSON in Golang using pq driver?

419 Views Asked by At

I wrote a query to show data from consumer table. Table does have a payment_methods field with type JSON. When i execute update query, its working fine. But i can't find out why error occured to fetch all data.

When i try to run this and this happen: sql: Scan error on column index 7, name "payment_methods": unsupported Scan, storing driver.Value type []uint8 into type *consumer.PaymentMethods

func ShowAll(context *fiber.Ctx) error {

    connector := config.InitConn()

    var consumerz = []Consumer{}
    var consumer Consumer

    rows, rowErr := connector.Query("SELECT mark, first_name, last_name, email, mobile, origin_country, pass, payment_methods, type, created, updated FROM consumer")

    if rowErr != nil {
        return context.Status(http.StatusInternalServerError).JSON(&fiber.Map{
            "status":  http.StatusInternalServerError,
            "message": rowErr.Error(),
            "data":    nil,
        })
    }

    for rows.Next() {

        loopErr := rows.Scan(
            &consumer.Mark,
            &consumer.FirstName,
            &consumer.LastName,
            &consumer.Email,
            &consumer.Mobile,
            &consumer.OriginCountry,
            &consumer.Pass,
            &consumer.PaymentMethods,
            &consumer.Type,
            &consumer.Created,
            &consumer.Updated,
        )

        if loopErr != nil {
            return context.Status(http.StatusInternalServerError).JSON(&fiber.Map{
                "status":  http.StatusInternalServerError,
                "message": loopErr.Error(),
                "data":    nil,
            })
        }

        consumerz = append(consumerz, consumer)
    }

    return context.Status(http.StatusOK).JSON(&fiber.Map{
        "status":  http.StatusOK,
        "message": "Хэрэглэгчийн жагсаалт",
        "data":    consumerz,
    })
}
```
`

**My struct is:**


```
package consumer

type PaymentMethods struct {
    Bank       string `json:"bank"`
    CardType   string `json:"card_type"`
    CardHolder string `json:"card_holder"`
    CardNumber uint   `json:"card_number"`
    Cvv        uint   `json:"cvv"`
    Exp        string `json:"exp"`
}

type Consumer struct {
    Mark           string          `json:"mark"`
    FirstName      *string         `json:"first_name"`
    LastName       *string         `json:"last_name"`
    Email          *string         `json:"email"`
    Mobile         *string         `json:"mobile"`
    OriginCountry  *string         `json:"origin_country"`
    Pass           *string         `json:"pass"`
    PaymentMethods *PaymentMethods `json:"payment_methods"`
    Type           *string         `json:"type"`
    Created        *string         `json:"created"`
    Updated        *string         `json:"updated"`
}

```
0

There are 0 best solutions below