我想在 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?
编辑:如果 arr3 已经存在,命令应该改变它的值。不应添加重复的 {"arr3":"3"}。
最佳答案
对数组使用连接运算符||
:
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
关于sql - 向 Json 数组添加新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54905672/