Created
June 14, 2016 12:24
-
-
Save villelahdenvuo/5b1fbbf3f22853475bba14f8833faada to your computer and use it in GitHub Desktop.
PostgreSQL jsonb_set is nice, but it does't create missing objects so I made this little helper.
This file contains hidden or 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 | |
-- Create missing objects in the path. | |
FOREACH k IN ARRAY path LOOP | |
p := p || k; | |
IF (target #> p IS NULL) THEN | |
target := jsonb_set(target, p, '{}'::jsonb); | |
END IF; | |
END LOOP; | |
-- Set the value like normal. | |
RETURN jsonb_set(target, path, val); | |
END; | |
$$ LANGUAGE plpgsql; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It was pretty useful to include the ability to concatenate or merge objects (the
||
operator). Without that, the calling code is pretty verbose. This one should support arrays and act more like json_set. I'm not sure about older versions like pg9 but there are some short example SQLs included below.