sql - 如何使用数据将数组更改为 jsonb?
问题描述
我有这样的数据数组列:
{foo,bar}
{foo}
{foo,foobar}
...
我想将其转换为 jsonb:
[{"my_key": "foo", "state": true}, {"my_key": "bar", "state": true}]
[{"my_key": "foo", "state": true}]
[{"my_key": "foo", "state": true}, {"my_key": "foobar", "state": false}]
...
“状态”在哪里
case when type = ANY('{"foo","bar"}'::text[]) then true
else false
我怎样才能做到这一点?谢谢
解决方案
您可以取消嵌套值并使用横向连接将它们聚合回来:
with t (data) as (
values
(array['foo','bar']),
(array['foo']),
(array['foo', 'foobar'])
)
select x.*
from t
cross join lateral (
select jsonb_agg(jsonb_build_object(
'my_key', x.type,
'state', x.type = any(array['foo','bar']))
) as val
from unnest(t.data) as x(type)
) x;
返回:
val
------------------------------------------------------------------------
[{"state": true, "my_key": "foo"}, {"state": true, "my_key": "bar"}]
[{"state": true, "my_key": "foo"}]
[{"state": true, "my_key": "foo"}, {"state": false, "my_key": "foobar"}]
推荐阅读
- asp.net-core - 创建 Service Fabric Api 服务仅允许 ASP .NET Core 2.1
- typescript - 在标记的联合中提取联合类型
- python - 使用烧瓶 restful 允许 AWS windows 实例上的流量
- r - 如何在标签集之后添加水平线而不在 RMarkdown 的 TOC 中创建空白条目?
- c - 是否有编译器选项可用于将堆栈变量初始化为非零值(毒药)以帮助调试?
- gekko - Gekko 非线性混合整数规划。设置目标函数的问题
- bash - 将文件的权限(八进制)与 Bash Shell 中的整数进行比较
- email - 如果我的域中不存在电子邮件地址,则创建它
- wordpress - Elementor 中的响应式文本大小、图像大小和布局
- php - 下单后缺货时自动为产品添加特定类别和标签