Search code examples
sqlpostgresqljsonb

Remove json object from array of jsons in postgres


I have the following json in my column in posgres database.

Column items in table products

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

I want to delete json object using jsonb

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

I try this:

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

I tried different approaches but nothing work correctly.


Solution

  • The "minus" operator doesn't work on objects, only keys. And it doesn't work on arrays of objects either.

    I would write a function that removes a single object from an array.

    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;
    

    Then you can use it like this:

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

    Online example