【问题标题】:how to populate nested composite type from JSON and insert into a table如何从 JSON 填充嵌套复合类型并插入到表中
【发布时间】:2017-09-22 15:11:13
【问题描述】:

我正在尝试将复杂的 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 兼容数组,但这仍然不起作用,因为存在类型转换问题。

所以,我真的想在这里解决两个问题:-

  1. 如何将 JSON 转换为 json_populate_recordset 喜欢的兼容 JSON,即将复杂的 JSON 序列化为一个类型(在我们的例子中为 ty)。

  2. 在尝试转换和插入类型的 ARRAY 时如何解决类型转换问题。

【问题讨论】:

    标签: postgresql postgresql-9.6 postgresql-json


    【解决方案1】:

    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)
    

    【讨论】:

    • 感谢 Clodoaldo。虽然实现起来非常复杂,但它确实有效。
    猜你喜欢
    • 2015-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多