U
U
Urbansamurai2021-10-14 13:11:07
PostgreSQL
Urbansamurai, 2021-10-14 13:11:07

How to remove an element from a JSONB array by index?

I tried this option

UPDATE group_settings SET group_recepients = array_remove(group_recepients, item_to_remove) 
    FROM (
        SELECT arr.item_object as item_to_remove
        FROM group_settings,
        jsonb_array_elements(group_recepients) WITH ordinality arr(item_object, position) 
        WHERE customer_group_id is NULL AND arr.position=1
    )
    WHERE customer_group_id IS NULL AND user_id = '...';


but it gives a very strange error:
ERROR: unknown signature: array_remove(jsonb, jsonb) (desired jsonb)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
galaxy, 2021-10-14
@Urbansamurai

If group_recipients is a JSON object or an array, then through the "-" operator (in the case of an object it removes by key, in the case of an array - by value):

postgres=# select '{"email": "[email protected]", "telegram_token": "", "telegram_user_id":""}'::jsonb - 'email';
                    ?column?
------------------------------------------------
 {"telegram_token": "", "telegram_user_id": ""}
(1 row)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question