递归展平postgres中的嵌套jsonb,而没有未知的深度和未知的关键字段

ros*_*eve 3 postgresql jsonb

我如何在不知道深度和每个深度的字段中递归地展平嵌套的jsonb?(请参见下面的示例)

进行扁平化的Postgressql查询会非常准确

    {
       "xx": "",
       "xx": "",
       "form": "xxx",
       "type": "",
       "content_type": "xxx",
       "reported_date": ,
       "contact": {
           "imported_date": "",
           "name": "",
           "phone": "",
           "alternate_phone": "",
           "specialization": "",
           "type": "",
           "reported_date": ,
           "parent": {
               "_id": "xxx",
               "_rev": "xxx",
               "parent": "",
               "type": "xxx" 
               } 
        }
    }
Run Code Online (Sandbox Code Playgroud)

我已经在堆栈溢出中进行了搜索,但是他们只考虑具有单个深度的jsonb,并且之前已经知道密钥

kli*_*lin 5

设置示例:

create table my_table(id int, data jsonb);
insert into my_table values
(1,
$${
   "type": "a type",
   "form": "a form",
   "contact": {
       "name": "a name",
       "phone": "123-456-78",
       "type": "contact type",
       "parent": {
           "id": "444",
           "type": "parent type" 
           } 
    }
}$$);
Run Code Online (Sandbox Code Playgroud)

递归查询jsonb_each()针对任何级别上找到的每个json对象执行。新键名包含从根开始的完整路径:

with recursive flat (id, key, value) as (
    select id, key, value
    from my_table,
    jsonb_each(data)
union
    select f.id, concat(f.key, '.', j.key), j.value
    from flat f,
    jsonb_each(f.value) j
    where jsonb_typeof(f.value) = 'object'
)
select id, jsonb_pretty(jsonb_object_agg(key, value)) as data
from flat
where jsonb_typeof(value) <> 'object'
group by id;

 id |                   data                   
----+------------------------------------------
  1 | {                                       +
    |     "form": "a form",                   +
    |     "type": "a type",                   +
    |     "contact.name": "a name",           +
    |     "contact.type": "contact type",     +
    |     "contact.phone": "123-456-78",      +
    |     "contact.parent.id": "444",         +
    |     "contact.parent.type": "parent type"+
    | }
(1 row)
Run Code Online (Sandbox Code Playgroud)

如果您想获得此数据的平面视图,可以使用create_jsonb_flat_view()此答案中描述的功能展平来自JSONB字段的聚合键/值对?

您需要使用展平的jsonb创建表(或视图):

create table my_table_flat as 
-- create view my_table_flat as 
with recursive flat (id, key, value) as (
-- etc as above
-- but without jsonb_pretty()
Run Code Online (Sandbox Code Playgroud)

现在,您可以在表上使用该函数:

select create_jsonb_flat_view('my_table_flat', 'id', 'data');

select * from my_table_flat_view;


 id | contact.name | contact.parent.id | contact.parent.type | contact.phone | contact.type |  form  |  type  
----+--------------+-------------------+---------------------+---------------+--------------+--------+--------
  1 | a name       | 444               | parent type         | 123-456-78    | contact type | a form | a type
(1 row)
Run Code Online (Sandbox Code Playgroud)

该解决方案在Postgres 9.5+中有效,因为它使用了此版本中引入的jsonb函数。如果您的服务器版本较旧,强烈建议无论如何都要升级Postgres以有效使用jsonb。