sql - 如何从 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...
我知道有一个"-"
运算符,允许消除特定属性,但是有一个完全相反的运算符吗?
解决方案
在琐碎的情况下,您可以使用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中测试它。
推荐阅读
- java - 无需多组源代码的多版本jar文件
- asp.net-core - 如何从 Polly 重试更改 HttpMessageHandler 的配置?
- reactjs - 将鼠标悬停在元素上时工具提示显示在错误的位置
- spring - 在 Spring Rest Service 中自定义 XML 输出
- css - 如何使用剪辑路径或任何其他方式在 css 中创建以下形状
- apache-kafka - 卡夫卡流抑制在窗口化后不产生输出
- android - 应用程序字体大小不会改变
- javascript - 使用Javascript从两个对象数组中删除重复项
- python - 如何在 Python 中使用整数变量重命名文本文件?
- python - 'pytype' 为使用 TypeVar 的函数引发 FAILED