我正在尝试将复杂的 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 数组填充到复合类型中然后将其插入来将其插入表中。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 兼容数组,但这仍然不起作用,因为存在类型转换问题。
所以,我真的想在这里解决两个问题:-
如何将 JSON 转换为 json_populate_recordset 喜欢的兼容 JSON,即复杂的 JSON 被序列化为一个类型(在我们的例子中是 ty)。
尝试转换和插入类型数组时如何解决类型转换问题。