arrays - 将多个 Json 数组转换为单个数组,而不是父数组中的数组
问题描述
我在 2 行中有以下 2 个 Json。
{
"attributes": [{
"name": "text-1580797977710",
"value": "Nikesh Niroula"
}, {
"name": "email-1580797979166",
"value": "nikesh@gmail.com"
}]
}
{
"attributes": [{
"name": "text-1580797977720",
"value": "Denver"
}, {
"name": "text-1580797977723",
"value": "colarado"
},
{
"name": "text-1580797977727",
"value": "USA"
}
]
}
我需要使用 postgresql 将上述 json 聚合到一个数组中,预期结果如下。我尝试使用 json_agg 但这会在主数组中添加一个内部数组。可能有多个 json 而不仅仅是 2 个。
{
"attributes": [{
"name": "text-1580797977710",
"value": "Nikesh Niroula"
}, {
"name": "email-1580797979166",
"value": "nikesh@gmail.com"
}, {
"name": "text-1580797977720",
"value": "Denver"
}, {
"name": "text-1580797977723",
"value": "colarado"
},
{
"name": "text-1580797977727",
"value": "USA"
}
]
}
解决方案
在将它们提供给 agg 函数之前,您需要取消嵌套它们。如果表是“j”,列是“x”,那么:
select jsonb_build_object('attributes',jsonb_agg(value))
from j, jsonb_array_elements(x->'attributes');
推荐阅读
- asp.net-mvc - 在锚标签的href内使用@
- ios - 如何用内部框架创建框架?
- python - Django 使用替换的 Auth 模型引发操作错误
- php - 如何在 PHP 生成的表格顶部显示空行
- jquery - 导轨 axlsx 和 ajax
- java - 查找平均值/最小值/最大值
- wordpress - 所有自定义帖子类型的自定义 WordPress 永久链接结构均未更改
- node.js - 从 Digital Ocean Ubuntu Droplet 连接到 Mongo Atlas
- java - libgdx 控制器轴四舍五入到 1 或 -1
- c# - 遥测初始化程序从 .net 核心 MVC 应用程序添加请求正文内容以请求遥测属性不起作用