【发布时间】:2018-05-30 07:02:58
【问题描述】:
我正在尝试在 Postgres 中构建一个同时支持数组和对象的递归 CTE,以返回键值对列表,但似乎无法找到一个好的示例。这是我当前的代码。
with recursive jsonRecurse as
(
select
j.key as Path
,j.key
,j.value
from jsonb_each(to_jsonb('{
"key1": {
"key2": [
{
"key3": "test3",
"key4": "test4"
}
]
},
"key5": [
{
"key6":
[
{
"key7": "test7"
}
]
}
]
}'::jsonb)) j
union all
select
jr.path || '.' || jr2.Key
,jr2.key
,jr2.value
from jsonRecurse jr
left join lateral jsonb_each(jr.value) jr2 on true
where jsonb_typeof(jr.value) = 'object'
)
select
*
from jsonRecurse;
正如您所见,只要我点击一个数组而不是一个对象,代码就会停止递归。我尝试过使用 case 语句,并将对 jsonb_each 或 jsonb_array_element 的函数调用放在 case 语句中,但我收到一个错误,告诉我改用横向连接。
【问题讨论】:
标签: postgresql jsonb recursive-cte