如何将字符串插入jsonb类型postgres?

我有一个函数,它为批处理插入到Postgres生成一个准备好的语句,在这里我试图将字符串插入Postgres中的jsonb类型。

我的结构:

type struct1 struct {
id int
comment string
extra string
}

我的表模式如下所示:

create table deal (
id bigserial,
comment varchar(75),
extra jsonb
)

我想将[]struct 1转储到Postgres DB“Deal”。

生成准备语句的函数如下所示:

func BulkInsert(str []struct1, ctx context.Context) string {
    log.Debug("inserting records to DB")
    query := fmt.Sprintf(`insert into deal (%s) values `, strings.Join(dbFields, ","))
    var numFields = len(dbFields)
    var values []interface{}
    for i, database := range str {
        values = append(values, database.Comment,`'`+database.Extra+`'`)
        n := i * numFields
        query += `(`
        for j := 0; j < numFields; j++ {
            query += `$` + strconv.Itoa(n+j+1) + `,`
        }
        query = query[:len(query)-1] + `),`
    }
    query = query[:len(query)-1]
        return query

预期的结果应该是:我能够将字符串插入json,或者可以说将字符串转换为json并转储。

但真实结果是: could not save batch: pq: invalid input syntax for type json"

Function of json_build_array('exp1'::Text, 'exp2'::Text) may help you.

return json object: {'exp1', 'exp2'}

And extract the values just use operator ->><index> like ->>1 to get 'exp2'.

If you just want to insert into database, function of to_json('any element') should also works, which can convert any element to a json object.

And you can get more funtions about json(jsonb) in postgres document.