Мне нужно, чтобы генерировать полный путь ко всем вложенным json значениям. Уровень потомков не ограничен.
Создание примеров данных:
drop table if exists test_nested;
create table test_nested (my_jsonb jsonb);
insert into test_nested values(
'{
"name": "Jon",
"last_name": "Smith",
"address": {
"country": "USA",
"city": "Miami"
},
"legal_address": {
"country": "Brazil",
"city": "Rio"
}
}');
Я могу получить все вложенные ключи и значения, но где я застрял, как получить полный путь ко всем этим ключам?
Вот что у меня есть:
with recursive get_keys (k, obj, val) as (
select t.k, case jsonb_typeof(test_nested.my_jsonb -> t.k) when 'object' then test_nested.my_jsonb -> t.k else null end, -- just get it's nested or not
test_nested.my_jsonb->t.k
from test_nested
cross join jsonb_object_keys(test_nested.my_jsonb) as t(k)
union all
select t.k, case jsonb_typeof(get_keys.obj -> t.k) when 'object' then get_keys.obj -> t.k else null end,
get_keys.obj->t.k
from get_keys
cross join jsonb_object_keys(get_keys.obj) as t(k)
)
select k, val, obj
from get_keys;
это дает:
k | val
---------------------------
name | Jon
last_name | Smith
address | json_object_here
country | USA
city | Miami
legal_address | json_object_here
country | Brazil
city | Rio
Что мне нужно:
k | val | full_path
---------------------------------------------------
name | Jon | /
last_name | Smith | /
address | json_object_here | /
country | USA | address/
city | Miami | address/
legal_address | json_object_here | /
country | Brazil | legal_address/
city | Rio | legal_address/
Любая помощь очень ценится