duanhegn231318 2019-03-29 07:27
浏览 1111
已采纳

如何在Postgres中将元素添加到JSON字段数组

I'm trying to append data to an array that belongs to a json field in postgres. While using pgAdmin I know the following query works. ~

UPDATE lesson SET data =
    jsonb_set (data, '{pages, 999999}', '{"pageNum": 2, "pageType": "voc"}', True)
WHERE id = 2;

I am simply trying to get the above query to work via my rest api written in go. I am getting an error that reads "pq: invalid input syntax for type json".

my code is as follows~

_, err := db.Exec(`
    UPDATE lessons SET data =
        jsonb_set (data, '{pages, 999999}','{"pageNum": $1, "pageType": $2}', True) 
    WHERE id = $3`,
    pageNum, pageType, id) // variable types are int string int

I suspect that the postgres driver isn't interpolating the the $ parameters. It will work if I use fmt.Sprinf() for the whole query but I am trying to avoid SQL injection attacks, and would like to take advantage of the built in security measures of the go sql library.

For reference my data is structured as follows~ Lessons Table

Lessons
   id    int
   data  jsonb

Go structs:

type Lesson struct {
    ID    int    `json:"id"`
    Name  string  `json:"name"`
    Pages []Page  `json:"pages"`
}

type Page struct {
    PageNum    int  `json:"pageNum"`
    PageType   string `json:"pageType"`
  • 写回答

1条回答 默认 最新

  • doulao1934 2019-03-29 07:36
    关注

    You cannot use query parameters within a string in Postgres. Either pass the entire string to Postgres as single parameter:

    str := fmt.Sprintf('{"pageNum": %d, "pageType": %q}', pageNum, pageType)
    _, err := db.Exec(`
        UPDATE lessons SET data =
            jsonb_set (data, '{pages, 999999}', $1, True) 
        WHERE id = $2`,
        str, id) // variable types are int string int
    

    or use string concatenation to do it on the server side:

    _, err := db.Exec(`
        UPDATE lessons SET data =
            jsonb_set (data, '{pages, 999999}','{"pageNum": ' || $1 || ', "pageType": ' || $2 || '}', True) 
        WHERE id = $3`,
        pageNum, pageType, id) // variable types are int string int
    

    The best/safest, is probably the first approach, with full JSON marshaling in your client, rather than a simple fmt.Sprintf. I leave that as an exercise for the reader.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?