我正在尝试将复杂的JSON转换为复合类型。下面是一个例子
CREATE TYPE ty as(a int, b int[]);
CREATE TABLE ta(ab ty[]);
INSERT INTO ta(ab) values(ARRAY[ROW(1, ARRAY[1, 1])::ty, ROW(2, ARRAY[2, 2])::ty]);
select * from ta;
ab
-----------------------------------
{"(1,\"{1,1}\")","(2,\"{2,2}\")"}
(1 row)这个很好用。
现在,我试图将JSON数组插入到表中,方法是先将JSON数组填充到复合类型中,然后插入它。PostgreSQL函数正在抛出一个奇怪的错误。
INSERT INTO ta(ab) values (json_populate_recordset(null::ty[], '[{"a":3,"b":[3,33]},{"a":4,"b":[4,44]}]'));
ERROR: first argument of json_populate_recordset must be a row type
INSERT INTO ta(ab) values (json_populate_recordset(null::ty, '[{"a":3,"b":[3,33]},{"a":4,"b":[4,44]}]'));
ERROR: column "ab" is of type ty[] but expression is of type ty
LINE 1: INSERT INTO ta(ab) values (json_populate_recordset(null::ty,...
^
HINT: You will need to rewrite or cast the expression.这只是我正在分享的一个示例,实际的JSON是从其他几个函数中生成的。因此,我需要修复JSON,然后将其作为复合类型插入到表中。其中一个非常接近但不被插入的是:
INSERT INTO ta(ab) values (json_populate_recordset(null::ty, '[{"a":3,"b":"{3,33}"},{"a":4,"b":"{4,44}"}]'));
ERROR: column "ab" is of type ty[] but expression is of type ty
HINT: You will need to rewrite or cast the expression.注意如何将数组转换为PostgreSQL喜欢的与JSON兼容的数组,但由于存在类型转换问题,这仍然无法工作。
所以,我真的很想解决两个问题:-
发布于 2017-09-22 15:53:58
从jsonb_to_recordset构建类型和聚合
insert into ta (ab)
select
array_agg((
a,
(select array_agg(e::int) from jsonb_array_elements_text(b) jae(e))
)::ty)
from jsonb_to_recordset(
'[{"a":3,"b":[3,33]},{"a":4,"b":[4,44]}]'
) as v(a int, b jsonb)https://stackoverflow.com/questions/46367940
复制相似问题