我的结构看起来像:
type struct1 struct {
id int
comment string
extra string
}
我的表架构如下所示:
create table deal (
id bigserial,
comment varchar(75),
extra jsonb
)
我想将 []struct1 转储到 Postgres DB“交易”。
我生成准备好的语句的函数如下所示:
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 并转储它。
实际结果是:
无法保存批处理:pq:json 类型的输入语法无效”
最佳答案
json_build_array('exp1'::Text, 'exp2'::Text)
的功能可能对你有帮助。
return json object: {'exp1', 'exp2'}
然后使用运算符 ->><index>
提取值喜欢->>1
得到'exp2'。
如果你只想插入数据库,to_json('any element')
的函数应该也可以工作,它可以将任何元素转换为 json 对象。
你可以在postgres document 中获得更多关于json(jsonb) 的功能。 .
关于postgresql - 将字符串插入 jsonb 类型的 postgres,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57212155/