Skip to content

Instantly share code, notes, and snippets.

@pveierland
Created September 16, 2022 21:57
Show Gist options
  • Save pveierland/705d716181e5a07ea4d23fde76196e27 to your computer and use it in GitHub Desktop.
Save pveierland/705d716181e5a07ea4d23fde76196e27 to your computer and use it in GitHub Desktop.
jsonb_set_deep
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