我有一个从移动应用程序发送的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,可以是g,值是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吗?我需要它返回一个map[int]float32,而不是json。
发布于 2020-06-13 02:02:19
您需要实现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
}https://stackoverflow.com/questions/62348531
复制相似问题