Skip to content

Instantly share code, notes, and snippets.

@jonathanalves
Forked from yyscamper/jsonb_remove_keys.sql
Created April 4, 2020 13:24
Show Gist options
  • Save jonathanalves/b0218940379065669d281d961dab3111 to your computer and use it in GitHub Desktop.
Save jonathanalves/b0218940379065669d281d961dab3111 to your computer and use it in GitHub Desktop.
PostgreSQL: Remove Multiple Keys From JSONB
CREATE OR REPLACE FUNCTION jsonb_remove_keys(
jdata JSONB,
keys TEXT[]
)
RETURNS JSONB AS $$
DECLARE
result JSONB;
len INT;
target TEXT;
BEGIN
len = array_length(keys, 1);
result = jdata;
FOR i IN 1..len LOOP
target = keys[i];
IF (jdata ? target) THEN
result = (result - target);
END IF;
END LOOP;
RETURN result;
END;
$$ LANGUAGE plpgsql;
@jonathanalves
Copy link
Author

Usage

SELECT
  jsonb_remove_keys(
    '{"cityname": "haha", "id": 123, "name": {"foo": 222}}'::jsonb,
    ARRAY['name', 'cityname'])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment