json - 将新对象添加到 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}';
但它正在替换以前的值。由于我是这个主题的新手,任何人都可以帮助以正确的方式去做。
解决方案
jsonb_insert()
是你的功能
UPDATE mytable
SET jsondata =
jsonb_insert(jsondata, '{testEvents,0}', '{"id":113070, "name1":"test2","count":18}');
第二个参数定义必须插入新元素的路径。0
是第一个位置。
推荐阅读
- php - 使用 PHP 进行 Flutter Firebase 消息传递
- python - 仅在启用调试模式时获取 ModuleNotFoundError
- mysql - 减少从 MYSQL DB 中获取数据的时间(表 150,000 中的记录)
- python - 在 python 中,我应该添加什么来从我的(文本文件)或我的(xml 文件)中获取包含 URL 列表的 URL?
- jquery - 无法从元素中删除属性
- javascript - 尝试使用量角器进行 SSH
- c# - ASP.NET CORE 没有 app.UseEndpoints() 方法
- jenkins - Jenkins Pipeline General Build Step - 动态传递值
- flutter - 导航器观察者在打开对话框时观察推送事件
- java - 在 Java 中使用子类项列表时如何避免向下转换