Tanner Semerad
Tanner Semerad

Reputation: 12672

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?

Upvotes: 0

Views: 1263

Answers (1)

Laurenz Albe
Laurenz Albe

Reputation: 246348

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

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

Upvotes: 3

Related Questions