1

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

5 Comments

@TheNightmare: works with your sample data: dbfiddle.uk/…
Yes, when i have two objects in information array, but when i have in array only one item to delete: '{"name": "second", "value": "medium"}' then function set my items to null. Example: dbfiddle.uk/…
@TheNightmare: what do you want then? An empty array? Remove the key information completely?
Empty array will be ok
Thx. Now looking fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.