Search code examples
postgresqljsonb

How to delete an array of keys from a Postgres jsonb object?


I have a jsonb object that I want to remove keys from. I have a jsonb array that holds the keys that I want to remove from the object. I see documentation for deleting a single key, like this:

SELECT '{"foo": true, "bar": false, "baz": true}'::jsonb - 'foo'

Returns {"bar": false, "baz": true}

But I don't see any documentation on removing multiple keys at once, say from a Postgres or jsonb array. I'd like to do something along the lines of this pseudocode:

SELECT '{"foo": true, "bar": false, "baz": true}'::jsonb - '["foo", "bar"]'::jsonb
-- I'd like to return {"baz": true}

How can I delete an array of keys from a jsonb object?


Solution

  • Use the - operator with an array of text on the right hand side:

    SELECT '{"foo": true, "bar": false, "baz": true}'::jsonb
           - '{foo,bar}'::text[];