首页 > 解决方案 > 将新对象添加到 jsonb 列下的 json 数组

问题描述

我在 postgres 表中有 jsonb 数据类型列“payload”,其值如下:

{"testEvents": [
        {
            "id": 113068,
            "name1": "test",
            "count": 15
        },
        {
            "id": 113069,
            "name1": "test1",
            "count": 15
        }
    ]
}

现在我想通过再添加一个 jsonobject 来更新内部 jsonarray。所以,我的结果会像

{"testEvents": [
        {
            "id": 113068,
            "name1": "test",
            "count": 15
        },
        {
            "id": 113069,
            "name1": "test1",
            "count": 15
        }
        ,
        {
            "id": 113070,
            "name1": "test2",
            "count": 18
        }
    ]
}

我尝试了以下查询:

UPDATE table SET payload = payload ||'{"id":113070,"name1":"test2","count":18}';

但它正在替换以前的值。由于我是这个主题的新手,任何人都可以帮助以正确的方式去做。

标签: jsonpostgresqljsonbpostgresql-9.5

解决方案


jsonb_insert()是你的功能

演示:db<>小提琴

UPDATE mytable
SET jsondata =
    jsonb_insert(jsondata, '{testEvents,0}', '{"id":113070, "name1":"test2","count":18}');

第二个参数定义必须插入新元素的路径。0是第一个位置。


推荐阅读