首页 > 解决方案 > 将多个 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"
            }
        ]

     }

标签: arraysjsonpostgresqlpostgresql-9.5

解决方案


在将它们提供给 agg 函数之前,您需要取消嵌套它们。如果表是“j”,列是“x”,那么:

select jsonb_build_object('attributes',jsonb_agg(value))
   from j, jsonb_array_elements(x->'attributes');

推荐阅读