You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
create or replacefunctionpublic.jsonb_unnest_recursive(arr_data jsonb[])
53
+
returns table(
54
+
pathtext[],
55
+
value jsonb,
56
+
member_of text
57
+
)
58
+
immutable
59
+
returns nullonnull input -- = strict
60
+
parallel safe -- Postgres 10 or later
61
+
security invoker
62
+
language sql
63
+
set search_path =''
64
+
as $func$
65
+
--explain (analyse)
66
+
with recursive r (path, value, member_of) as
67
+
(
68
+
select
69
+
array[k.key],
70
+
v.value,
71
+
t.type
72
+
from unnest(arr_data) as u(data)
73
+
cross join jsonb_typeof(u.data) as t(type)
74
+
left join jsonb_each(case t.type when 'object' then u.data end) as o(obj_key, obj_value) on true
75
+
left join jsonb_array_elements(case t.type when 'array' then u.data end) with ordinality as a(arr_value, arr_key) on true
76
+
cross join coalesce(o.obj_key, (a.arr_key-1)::text) as k(key)
77
+
cross join coalesce(o.obj_value, a.arr_value) as v(value)
78
+
wheret.typein ('object', 'array')
79
+
andk.keyis not null
80
+
union all
81
+
select
82
+
array_append(r.path, k.key),
83
+
v.value,
84
+
t.type
85
+
from r
86
+
cross join jsonb_typeof(r.value) as t(type)
87
+
left join jsonb_each(case t.type when 'object' then r.value end) as o(obj_key, obj_value) on true
88
+
left join jsonb_array_elements(case t.type when 'array' then r.value end) with ordinality as a(arr_value, arr_key) on true
89
+
cross join coalesce(o.obj_key, (a.arr_key-1)::text) as k(key)
90
+
cross join coalesce(o.obj_value, a.arr_value) as v(value)
91
+
wheret.typein ('object', 'array')
92
+
andk.keyis not null
93
+
)
94
+
select r.*
95
+
from r
96
+
where jsonb_typeof(r.value) not in ('object', 'array');
97
+
$func$;
98
+
99
+
comment on function public.jsonb_unnest_recursive(arr_data jsonb[]) is 'Recursive parse nested JSONs (arrays and objects), returns keys and its values';
0 commit comments