首页 > 解决方案 > 如何从 PostgreSQL 返回“稀疏”json(选择多个属性)

问题描述

MongoDB 有一种方法可以选择作为查询结果返回的 JSON 文档的字段。我正在寻找与 PostgreSQL 相同的东西。

假设我有一个这样的 JSON:

{
a: valuea,
b: valueb,
c: valuec,
...
z: valuez
}

特定值可以是简单值或具有进一步嵌套的子对象。

我希望有一种方法可以返回仅包含我选择的属性的 JSON 文档,例如:

SELECT json_col including_only a,b,c,g,n from table where... 

我知道有一个"-"运算符,允许消除特定属性,但是有一个完全相反的运算符吗?

标签: sqljsonpostgresql

解决方案


在琐碎的情况下,您可以使用jsonb_to_record(jsonb)

with data(json_col) as (
values
('{"a": 1, "b": 2, "c": 3, "d": 4}'::jsonb)
)

select *, to_jsonb(rec) as result
from data
cross join jsonb_to_record(json_col) as rec(a int, d int)

             json_col             | a | d |     result
----------------------------------+---+---+------------------
 {"a": 1, "b": 2, "c": 3, "d": 4} | 1 | 4 | {"a": 1, "d": 4}
(1 row)

请参阅JSON 函数和运算符。

如果您需要更通用的工具,该功能可以完成工作:

create or replace function jsonb_sparse(jsonb, text[])
returns jsonb language sql immutable as $$
    select $1 - (
        select array_agg(key)
        from jsonb_object_keys($1) as key
        where key <> all($2)
        )
$$;

-- use:
select jsonb_sparse('{"a": 1, "b": 2, "c": 3, "d": 4}', '{a, d}')

在db<>fiddle中测试它。


推荐阅读