亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將 golang 地圖插入 PostgreSQL

如何將 golang 地圖插入 PostgreSQL

Go
慕容森 2022-06-13 10:20:50
我有一個從移動應用程序發送的 json 對象,如下所示:{    "product_id": "0123456789",    "name": "PRODUCT_NAME",    "manufacturer": "PRODUCT_MANUFACTURER",    "image_url": "IMAGE_URL",    "additional_info": "",    "store_id": "STORE_ID",    "store_name": "STORE_NAME",    "owner_id": "OWNER_ID",    "quantities": {        "1000": 10.0,        "1500": 12.0,    }}中的鍵值quantities是a,例如可以是克,值是a代表價格。因此,例如,1000 克大米將花費 10 美元,而 1500 克大米將花費 12.0 美元(作為銷售或其他東西)我的Go代碼中有一個模型對象,quantities當map[int]float32 我試圖找到一種方法將此地圖插入到PostgreSQL我擁有的數據庫中時,它具有該文件,但無法弄清楚如何。這是我的Go模型:type Product struct {    ID             string              UUID           string              Name           string             Manufacturer   string             ImageURL       string             AdditionalInfo string              StoreID        string             StoreName      string              OwnerID        string              Quantities     map[int]float32}我讀過但是當我檢索數據時JSONB它不會返回嗎?json我需要它返回 amap[int]float32而不是json。
查看完整描述

1 回答

?
湖上湖

TA貢獻2003條經驗 獲得超2個贊

您需要實現driver.Valuer和sql.Scanner接口以保存為 JSONB


接口,以便將driver.Valuer對象編組為數據庫可以理解的 JSON 字節切片。


sql.Scanner接口,這樣它將數據庫中的 JSON 字節切片解組到結構字段中。


而對于 json Marshal 你需要轉換map[int]float32成map[string]float32


type cusjsonb map[int]float32


// Returns the JSON-encoded representation

func (a cusjsonb) Value() (driver.Value, error) {

    // Convert to map[string]float32 from map[int]float32 

    x := make(map[string]float32)

    for k, v := range a {

       x[strconv.FormatInt(int64(k), 10)] = v

    }

    // Marshal into json 

    return json.Marshal(x)

}


// Decodes a JSON-encoded value

func (a *cusjsonb) Scan(value interface{}) error {

    b, ok := value.([]byte)

    if !ok {

        return errors.New("type assertion to []byte failed")

    }

    // Unmarshal from json to map[string]float32

    x := make(map[string]float32)

    if err := json.Unmarshal(b, &x); err != nil {

       return err

    }

    // Convert to map[int]float32 from  map[string]float32

    *a = make(cusjsonb, len(x))

    for k, v := range x {

      if ki, err := strconv.ParseInt(k, 10, 32); err != nil {

         return err

      } else {

         (*a)[int(ki)] = v

      }

    }

    return nil

}


查看完整回答
反對 回復 2022-06-13
  • 1 回答
  • 0 關注
  • 94 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號