首页 > 解决方案 > 如何只保留键数组中存在的 Postgres jsonb 对象的属性?

问题描述

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

如果我的对象是:

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

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

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

我怎样才能做到这一点?

标签: jsonpostgresqljsonb

解决方案


借用这个答案......

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) 列的表,然后可以正常查询。

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

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


推荐阅读