json - Postgres - 将两个数组合并成一个 JSON

标签 json postgresql

我有两个像这样的 text[] 列:

Col1:
{itema, itemb, itemc}

Col2
{valuea, valueb, valuec}

如何将这两个数组合并到一个 json 中?像这样:

{"itema":"valuea", "itemb":"valueb", "itemc":"valuec"}

最佳答案

使用unnest将数组转换为行。

select unnest(col1) as col1, unnest(col2) as col2
from test;

 col1  |  col2  
-------+--------
 itema | valuea
 itemb | valueb
 itemc | valuec

然后在 jsonb_object_agg 的子查询中使用它将行聚合在一起作为键/值对。

select jsonb_object_agg(col1, col2)
from (
  select unnest(col1) as col1, unnest(col2) as col2
  from test
) t;
                        jsonb_object_agg                         
----------------------------------------------------------------
 { "itema" : "valuea", "itemb" : "valueb", "itemc" : "valuec" }

关于json - Postgres - 将两个数组合并成一个 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57262124/

相关文章:

java - 如何在 Jersey-Test 中发布 JSON 请求

ruby - 如何在 Ruby 中用单引号 (') 解析 JSON 字符串?

ios - 如何在 Objective C 中从 NSArray 中获取元素

postgresql - 在 PostgreSQL 上使用条件计数

sql - TotalCount 基于仍然需要获取的列

postgresql - Entity Framework 连接到 postgres : "The underlying provider failed on Open" 失败

json - 如何获取|在Flutter中将json数据加载到List <myClass>确实可以吗?

python - 字典的嵌套列表

c++ - 不在 C++ 程序中使用 libpq 检索 NOTIFY

java - Hibernate 与 postgres 发生异常,无法找到表