ERROR: cannot deconstruct an array as an object

ERROR: cannot deconstruct an array as an object

这个问题是

的后续问题

我有以下 table 示例记录:

create table jtest
(
    id int,
    jcol json
);

insert into jtest values(1,'[{"name":"Jack","address1":"HNO 123"}]');
insert into jtest values(1,'[{"address2":"STREET1"}]');
insert into jtest values(1,'[{"address3":"UK"}]');

select * from jtest;

id      jcol
-------------------------------------------
1       [{"name":"Jack","address":"HNO 123 UK"}]
1       [{"address2":"STREET1"}]
1       [{"address3":"UK"}]

预期结果:

id      jcol
--------------------------------------------------------------------------------------------
1       [{"name":"Jack","address":"HNO 123 UK", "address2":"STREET1", "address3":"UK"}]

尝试了以下查询:

select id,json_agg(jcol) as jcol 
from jtest
group by id;

但是得到的结果出乎意料:

id      jcol
--------------------------------------------------------------------------------------------
1       [[{"name":"Jack","address":"HNO 123 UK"}], [{"address2":"STREET1"}], [{"address3":"UK"}]]   

尝试了 S-Man 答案:

SELECT
    id,
    json_object_agg(key, value)  
FROM
    jtest,
    json_each(jcol)              
GROUP BY id;

出现错误:

ERROR: cannot deconstruct an array as an object

如果您的所有数组都包含一个对象,如示例数据所示,您可以:

select t.id, jsonb_build_array(json_object_agg(x.k, x.v))
from jtest t
cross join lateral json_each(t.jcol -> 0) as x(k, v)            
group by t.id;

这与您的原始代码的逻辑基本相同,只是它在 json_each() 之前获取数组中的第一个(唯一)对象。