[英]Remove nested json object from array in postgres
I have a json object field in postgres that has the following shape我在 postgres 中有一个 json object 字段,具有以下形状
{
"a": {
},
"b": [
{
}
],
"c": {
"d": "",
"e": [
{
"id": 1234,
"f": "",
"g": ""
}
]
}
} }
I'd like to know how to write a statement that removes object's from e array where the id is 1234 in postgres.我想知道如何编写一个语句,从 postgres 中 id 为 1234 的 e 数组中删除对象。 e could have multiple objects, if there are more than one objects in the e array, I want to keep those and only remove the object with the id of 1234.
e 可以有多个对象,如果 e 数组中有多个对象,我想保留这些对象,并且只删除 id 为 1234 的 object。
Thanks谢谢
step-by-step demo:db<>fiddle 分步演示:db<>fiddle
UPDATE t
SET data = jsonb_set(data::jsonb, '{c,e}', s.new_array::jsonb)::json -- 4
FROM (
SELECT
json_agg(value) as new_array -- 3
FROM
t,
json_array_elements(data -> 'c' -> 'e') -- 1
WHERE value ->> 'id' != '1234' -- 2
) s;
UPDATE
on your table, you could use the jsonb_set()
function to update the JSON element with your newly created array.UPDATE
,你可以使用jsonb_set()
function 用你新创建的数组更新 JSON 元素。 Unless you are not using type jsonb
, you have to case your JSON data into jsonb
(and the result back to type json
)jsonb
,否则您必须将您的 JSON 数据转换为jsonb
(并将结果返回类型json
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.