Created
February 26, 2018 09:07
Star
You must be signed in to star a gist
PostgreSQL: Rename JSONB Keys (Batch Mode)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE OR REPLACE FUNCTION jsonb_rename_keys( | |
jdata JSONB, | |
keys TEXT[] | |
) | |
RETURNS JSONB AS $$ | |
DECLARE | |
result JSONB; | |
len INT; | |
newkey TEXT; | |
oldkey TEXT; | |
BEGIN | |
len = array_length(keys, 1); | |
IF len < 1 OR (len % 2) != 0 THEN | |
RAISE EXCEPTION 'The length of keys must be even, such as {old1,new1,old2,new2,...}'; | |
END IF; | |
result = jdata; | |
FOR i IN 1..len BY 2 LOOP | |
oldkey = keys[i]; | |
IF (jdata ? oldkey) THEN | |
newkey = keys[i+1]; | |
result = (result - oldkey) || jsonb_build_object(newkey, result->oldkey); | |
END IF; | |
END LOOP; | |
RETURN result; | |
END; | |
$$ LANGUAGE plpgsql; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: jsonb_rename_keys(jdata, ARRAY['oldkey1', 'newkey1', 'oldkey2', 'newkey2', ....])
If old key doesn't exist, then simply ignore it.