Skip to content

Instantly share code, notes, and snippets.

@yyscamper
Created February 26, 2018 09:49
Show Gist options
  • Save yyscamper/1b8669ea224f3bea826f2100b0cfc108 to your computer and use it in GitHub Desktop.
Save yyscamper/1b8669ea224f3bea826f2100b0cfc108 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;
@yyscamper
Copy link
Author

yyscamper commented Feb 26, 2018

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