json - 如何只保留键数组中存在的 Postgres jsonb 对象的属性?
问题描述
我有一个jsonb
具有许多属性的对象,并且我有一个 Postgres 键数组,我想从对象中提取到一个新的、精简的对象中。
如果我的对象是:
'{"foo": true, "bar": 2, "baz": "cat", "other": "Some text"}'::jsonb
我要提取的属性数组是'{foo,other}'
,我想要的结果是:
'{"foo": true, "other": "Some text"}'::jsonb
我怎样才能做到这一点?
解决方案
借用这个答案......
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 对象中。
推荐阅读
- smtp - PMTA 到 PMTA 路由更改电子邮件标题
- apache-spark - Spark结构化流中的自定义窗口
- python - 通过 Scrapy 上的多个链接爬行
- python - 如果有人单击反应更改消息并删除反应 discord.py,则机器人不和谐
- csv - 发布工作表时如何仅显示过滤后的数据?
- python - 如何根据多列中的多个条件计算/求和值
- python - 计算 D 维空间中圆上两点之间的欧几里得距离
- python - 安装python IIS
- configuration - RubyMine 自定义 Ruby 配置中究竟需要包含什么,尤其是。用于调试?
- mime-types - 由于 mime 类型不匹配,CefSharp 无法下载 css