登录
首页 >  Golang >  Go问答

如何将 PostgreSQL 中的 jsonb 数据映射到 Golang 结构

来源:stackoverflow

时间:2024-02-22 12:18:27 425浏览 收藏

一分耕耘,一分收获!既然都打开这篇《如何将 PostgreSQL 中的 jsonb 数据映射到 Golang 结构》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!

问题内容

首先,我尝试了过去的 stackoverflow 答案中的解决方案,这些答案的问题与我的相关,但没有任何效果,这就是为什么我将其作为一个单独的问题提出。

我在 golang 中有两个结构

type otherpayments struct {
    debitto     int    `json:"debit_to" binding:"required"`
    creditfrom  int    `json:"credit_from" binding:"required"`
    overalltype string `json:"overall_type" binding:"required"`
}

type advanceandroompayment struct {
    pmid        int    `json:"pm_id" binding:"required"`        //payment method id
    pmname      string `json:"pm_name" binding:"required"`      //payment method name
    debitto     int    `json:"debit_to" binding:"required"`     //the ledger to debit from
    creditfrom  int    `json:"credit_from" binding:"required"`  //the ledger to credit from
    overalltype string `json:"overall_type" binding:"required"` //overall transaction type
}

我的 booking_settings postgresql 表中有 5 sql 列

  • initial 列,类型 = otherpaymentsjsonb
  • cancellation,类型 = otherpaymentsjsonb
  • updation,类型 = otherpaymentsjsonb
  • advance_ payment 类型 = advanceandroompaymentjsonb []
  • room_ payment,类型 = advanceandroompaymentjsonb []

select 查询如下

SELECT initial, cancellation, updation advance_payment, room_payment FROM booking_settings WHERE hotel_id = $1

我使用的sql包是https://jmoiron.github.io/sqlx/

我正在尝试将上面的列扫描到适当的结构变量中,到目前为止,我只能扫描 initial、cancel 和 updation,但不能扫描 jsonb [] advance_ payment 和 room_ payment

非常感谢任何帮助,谢谢


正确答案


以防万一您不知道,jsonb[] 是一个 postgresql 数组 类型,其元素类型为 jsonb。它不是“json 数组”类型。

如果您想将 json 数据存储在列中,则应使用 json/jsonb 类型,无论您希望该数据包含标量、对象还是数组 json 值。

因此,除非您选择考虑到某些特定用例的 postgresql 数组类型,否则最好将列的类型从 jsonb[] 更改为 jsonb

如果您不能或不想更改列类型,那么您仍然可以在 select 查询中将 postgresql 数组转换为 json 数组,然后在自定义 go sql.scanner 实现中,使用 json.unmarshal 解码数据库数据。

select to_jsonb(advance_payment) from booking_settings where hotel_id = $1
-- or
select array_to_json(advance_payment)::jsonb from booking_settings where hotel_id = $1
type advanceandroompaymentlist []advanceandroompayment

func (ls *advanceandroompaymentlist) scan(src any) error {
    var data []byte
    switch v := src.(type) {
    case string:
        data = []byte(v)
    case []byte:
        data = v
    }
    return json.unmarshal(data, ls)
}

如果您有许多查询引用 postgresql 数组列,并且您不想更新每个查询来进行转换,您可以自己解析 postgresql 数组,然后解组各个元素,或者您可以委托该操作致力于一些第三方实施。

这是一个使用 pq.GenericArray未经测试示例:

// i haven't tested the following but i'd assume it ought to work,
// if not, then perhaps maybe small tweaks are needed here and there...
type advanceandroompaymentlist []advanceandroompayment

func (ls *advanceandroompaymentlist) scan(src any) error {
    return pq.genericarray{ls}.scan(src)
}

// implement scanner for the element type of the slice
func (a *advanceandroompayment) scan(src any) error {
    var data []byte
    switch v := src.(type) {
    case string:
        data = []byte(v)
    case []byte:
        data = v
    }
    return json.unmarshal(data, a)
}

如果您想自己解析 postgresql 数组,那么您需要了解用于表示此类数组的语法。您可以找到相关文档here

数组值的外部文本表示由项目组成 根据 i/o 转换规则进行解释 数组的元素类型,加上指示数组的装饰 结构。装饰由大括号({ 和 })围绕 数组值加上相邻项之间的分隔符。这 分隔符通常是逗号 (,),但也可以是其他字符: 它由数组元素类型的typdelim 设置决定。 在 postgresql 发行版提供的标准数据类型中, 全部都使用逗号,但类型框除外,它使用分号 (;)。

因此,例如,如果您有包含 json-object、json-array、json-string 和 json-bool 的 pg-array,并且您选择了它,则将传递给的数组表示形式sql.scanner 实现将类似于:

{"{\"foo\": \"bar\"}","[\"foo\", \"bar\"]","\"foo bar\"",true}

今天关于《如何将 PostgreSQL 中的 jsonb 数据映射到 Golang 结构》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>