我想在json下面的a3中添加一个新的数组元素:
{
"a1": "e1",
"a2": {
"b1": "y1",
"b2": "y2"
},
"a3": [{
"arr1": "1"
},
{
"arr2": "2"
}
]
}
所以我希望上面的json像这样:
{
"a1": "e1",
"a2": {
"b1": "y1",
"b2": "y2"
},
"a3": [{
"arr1": "1"
},
{
"arr2": "2"
},
{
"arr3": "3"
}
]
}
我可以使用以下命令添加新元素。但是当涉及到数组时,我找不到添加新元素的方法。
SELECT jsonb_set('{ "a1": "e1", "a2": { "b1": "y1", "b2": "y2" }, "a3": [{ "arr1": "1" }, { "arr2": "2" }] }'::jsonb,
'{a2,b3}',
'"4"');
我要使用什么命令将{“ arr3”:“ 3”}添加到a3?
edit:如果arr3已经存在,则该命令应更改其值。不应添加重复的{“ arr3”:“ 3”}。
答案 0 :(得分:1)
对数组使用串联运算符||
:
with my_data(json_data) as (
values
('{ "a1": "e1", "a2": { "b1": "y1", "b2": "y2" }, "a3": [{ "arr1": "1" }, { "arr2": "2" }] }'::jsonb)
)
select jsonb_set(json_data, '{a3}', json_data->'a3' || '{"arr3": "3"}')
from my_data;
jsonb_set
---------------------------------------------------------------------------------------------------
{"a1": "e1", "a2": {"b1": "y1", "b2": "y2"}, "a3": [{"arr1": "1"}, {"arr2": "2"}, {"arr3": "3"}]}
(1 row)
检查键是否在嵌套数组中存在有点复杂。您应该使用jsonb_array_elements()
取消嵌套数组的操作:
with my_data(json_data) as (
values
('{ "a1": "e1", "a2": { "b1": "y1", "b2": "y2" }, "a3": [{ "arr1": "1" }, { "arr2": "2" }] }'::jsonb)
)
select
case when already_exists then json_data
else jsonb_set(json_data, '{a3}', json_data->'a3' || '{"arr3": "3"}')
end as json_data
from (
select json_data, bool_or(value ? 'arr3') as already_exists
from my_data
cross join jsonb_array_elements(json_data->'a3')
group by 1
) s