簡體   English   中英

從 postgres 的 json 數組中刪除 json object

[英]Remove json object from array of jsons in postgres

我在 posgres 數據庫的專欄中有以下 json 。

表格產品中的列項

{
    "name": "Super name",
    "type": "Green",
    "information": [
        {
            "name": "first",
            "value": "high"
        },
        {
            "name": "second",
            "value": "medium"
        }
    ],
}

我想使用 jsonb 刪除 json object

{
    "name": "second",
    "value": "medium"
}

我試試這個:

update products set items = jsonb_set(items, '{information}', (items->'information') - '{"name": "second", "value": "medium"}');

我嘗試了不同的方法,但沒有任何工作正常。

“減號”運算符不適用於對象,僅適用於鍵。 它也不適用於 arrays 對象。

我會寫一個 function 從數組中刪除單個 object。

create function remove_element(p_input jsonb, p_to_remove jsonb)
  returns jsonb
as
$$
  select coalesce(jsonb_agg(t.item order by t.idx), '[]')
  from jsonb_array_elements(p_input) with ordinality as t(item, idx)
  where t.item <> p_to_remove;
$$
language sql 
immutable;

然后你可以像這樣使用它:

update products
  set items = jsonb_set(items, '{information}', remove_element(items -> 'information', '{"name": "second", "value": "medium"}')) 
where ...

在線示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM