Created
September 16, 2022 21:57
-
-
Save pveierland/705d716181e5a07ea4d23fde76196e27 to your computer and use it in GitHub Desktop.
jsonb_set_deep
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_set_deep(target jsonb, path text[], val jsonb) | |
RETURNS jsonb AS $$ | |
DECLARE | |
k text; | |
p text[]; | |
BEGIN | |
IF (path = '{}') THEN | |
RETURN val; | |
ELSE | |
IF (target IS NULL) THEN | |
target = '{}'::jsonb; | |
END IF; | |
FOREACH k IN ARRAY path LOOP | |
p := p || k; | |
IF (target #> p IS NULL) THEN | |
target := jsonb_set(target, p, '{}'::jsonb); | |
ELSE | |
target := jsonb_set(target, p, target #> p); | |
END IF; | |
END LOOP; | |
RETURN jsonb_set(target, path, val); | |
END IF; | |
END; | |
$$ LANGUAGE plpgsql; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment