postgresql - 使用 PostgreSQL 在 NESTED JSONB 数组中添加对象
问题描述
json请求
INSERT INTO test.demotbl (data)
VALUES ('{
"x1": "Americas",
"x2": "West",
"x3": [{
"x_id": "sam"
}],
"x4": {
"a1": true,
"a2": false,
"a3": [
"xx",
"xx"
],
"a4": [
"Josh"
],
"y1": [{
"id": "RW",
"z2": true,
"z3": "USER"
},
{
"id": "RO",
"z2": false,
"z3": "SELECT"
}
]
}
}'::jsonb)
我想根据 id 条件 "id": "RO".Eample "z4": [{ "name": "john" }, { "name": "Steve" } 更新一个新归档的 z4
预期输出:
{
"x1": "Americas",
"x2": "West",
"x3": [{
"x_id": "sam"
}],
"x4": {
"a1": true,
"a2": false,
"a3": [
"xx",
"xx"
],
"a4": [
"Josh"
],
"y1": [{
"id": "RW",
"z2": true,
"z3": "USER"
},
{
"id": "RO",
"z2": false,
"z3": "SELECT",
"z4": [{
"name": "john"
},{
"name": "Steve"
}]
}
]
}
}
我可以使用什么 postgres JSONB sql 来实现上述输出?
解决方案
你应该可以这样做:
with zd as (select ('{x4,y1,'||index-1||',z3}')::text[] as path
from table1
,jsonb_array_elements((field1->>'x4')::jsonb->'y1')
with ordinality arr(x,index)
where x->>'id'='RO'
)
update table1
set field1=jsonb_set(field1,zd.path,'[{ "name": "john" }, { "name": "Steve" }]'::jsonb,true)
from zd
请注意,jsonb_set 中的最后一个参数现在为 true,如果该字段不存在,则指示它创建该字段。
最好的问候,
Bjarni
推荐阅读
- ios - 如何获取请求中标头的值 (URLSession.shared.dataTask(with: request) { (data, response, error)
- jinja2 - 使用支柱和 jinja 部署一些文件
- html - rtsp 不生成语音(直播)
- openstack - 在 openstack 上创建 Cinder 卷失败:未找到有效主机
- c# - .NET Core 2.0 Web API 中的 BSON
- wso2 - 如何在 WSO2 中获取文件名?
- powershell - 为什么 Write-Output 在 PowerShell 类方法中不起作用?
- kubernetes - 入口需要 Kubernetes 高端口
- sql - 在以下语句完成之前未提交 CTE 删除
- java - 在通过 REST Api 发送之前,java 是否会操纵地图中键的顺序?