postgresql jsonb 在对象中查找键

postgresql jsonb find key in object

我有一个 JSON 对象,可能如下所示:

{
    "key1" : "value1",
    "key2" : {
        "messagebody" : {
            "version" : "1"
        },
        "messageheader" : {
            "reference" : "a reference"
        }
    }
}

这存储在类型为 jsonb 的列中的 PostgeSQL table 中。我现在的目标是找到字段 version 和字段 reference。但是 json 的结构可能会有所不同,例如。 key2 可以在另一条记录中命名为 key3

PostgreSQL 中是否有一个查询允许我给它一个键并在对象中找到该键的值而不管它在对象中的位置?

PostgreSQL 版本为 10。

在 Postgres 10 中使用递归查询。

with recursive extract_all as
(
    select 
        key,
        value
    from my_table
    cross join lateral jsonb_each(jdata)
union all
    select
        obj_key,
        obj_value
    from extract_all
    left join lateral 
        jsonb_each(value) 
        as o(obj_key, obj_value) 
        on jsonb_typeof(value) = 'object'
    where obj_key is not null
)
select *
from extract_all
where key in ('version', 'reference')

Postgres 12+ 允许使用 SQL/JSON 路径的替代解决方案。

select
    'version' as key,
    jsonb_path_query(jdata, '$.**.version') as value
from my_table
union all
select
    'reference' as key,
    jsonb_path_query(jdata, '$.**.reference') as value
from my_table

Db<>fidlle.