Skip to content

Instantly share code, notes, and snippets.

@ruanmartinelli
Created March 24, 2020 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruanmartinelli/e2fc7d8b3fd51504d1cb2ac2c0fc3aed to your computer and use it in GitHub Desktop.
Save ruanmartinelli/e2fc7d8b3fd51504d1cb2ac2c0fc3aed to your computer and use it in GitHub Desktop.
create or replace function jsonb_merge_deep(jsonb,jsonb)
returns jsonb
language sql
immutable
as $func$
select case jsonb_typeof($1)
when 'object' then case jsonb_typeof($2)
when 'object' then (
select jsonb_object_agg(k, case
when e2.v is null then e1.v
when e1.v is null then e2.v
else jsonb_merge_deep(e1.v, e2.v)
end)
from jsonb_each($1) e1(k, v)
full join jsonb_each($2) e2(k, v) using (k)
)
else $2
end
when 'array' then $1 || $2
else $2
end
$func$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment