如何仅保留键数组中存在的 Postgres jsonb 对象的属性?

How to only keep properties from a Postgres jsonb object that exist in an array of keys?

我有一个具有许多属性的 jsonb 对象,并且我有一个 Postgres 键数组,我想从该对象中提取这些键到一个新的精简对象中。

如果我的对象是:

'{"foo": true, "bar": 2, "baz": "cat", "other": "Some text"}'::jsonb

我要提取的属性数组是 '{foo,other}',我想要的结果是:

'{"foo": true, "other": "Some text"}'::jsonb

我怎样才能做到这一点?

你可以这样做:

SELECT jsonb_object_agg(elem.key, elem.val)
FROM (jsonb_each(
         JSONB '{"foo": true, "bar": 2, "baz": "cat", "other": "Some text"}'
     ) AS elem(key, val)
   JOIN (unnest(
            TEXT[] '{foo,other}'
        ) AS filter(key) USING (key);

借用 ...

select jsonb_object_agg(key,value)
from jsonb_each('{"foo": true, "bar": 2, "baz": "cat", "other": "Some text"}'::jsonb)
where key = any('{foo,other}')

jsonb_each 将 JSON 变成 key (text) 和 value (jsonb) 列的 table,然后可以正常查询。

where key = any('{foo,other}') 基本上是 where key in ('foo', 'other') 但对于数组。

最后 jsonb_object_agg(key,value) 将所有匹配的行聚合到一个 JSON 对象中。