Postgres: Return json clob

Postgres: Return json clob

首先我在 Oracle 中有一个程序,其中 returns 一个 clob。这个 clob 包含一个 json 字符串,它是我用 pljson 从 sql-select 创建的。 像这样:

procedure xyz
(
    o_json out clob
)
is
    m_json_list json_list := json_list;
    m_json_temp json;
begin
    for cs in (select id, name, birthday from profile)loop
        m_json_temp := json;

        m_json_temp.put('id', cs.id);
        m_json_temp.put('name', cs.name);
        m_json_temp.put('birthday', cs.birthday);

        m_json_list.add(m_json_temp);
    end loop;
    o_json := convertToClob(m_json_list);
end xyz;

现在我想使用 Postgres 数据库获得相同的结果。 我发现的唯一原因是我有一个 table,其中一个 cloumn 的类型为 'json',并且包含整个 json。这不是我要找的。

谁能给我一个例子,说明如何在 postgre 中实现这种情况sql?

编辑: 以下是内部联接的示例:

procedure xyz
(
    o_json out clob
)
is
    m_json_list json_list := json_list;
    m_json_temp json;
begin
    for cs in (select ppf.id, ppf.name, ppf.birthday, ott.info from profile ppf inner join other_table ott on ott.ott_id = ppf.id )loop
        m_json_temp := json;

        m_json_temp.put('id', cs.id);
        m_json_temp.put('name', cs.name);
        m_json_temp.put('birthday', cs.birthday);
        m_json_temp.put('info', cs.info);

        m_json_list.add(m_json_temp);
    end loop;
    o_json := convertToClob(m_json_list);
end xyz;

因此,您正在寻找一种从查询构造 json 数组的方法。

给定一个 table 和一些测试数据:

postgres=# create table profile(id serial, name text, birthday date);
CREATE TABLE
postgres=# insert into profile(name, birthday) values('John', current_date - interval '30 years');
INSERT 0 1
postgres=# insert into profile(name, birthday) values('Jack', current_date - interval '25 years');
INSERT 0 1

您可以将行表示为 json 个对象,如下所示:

postgres=# select row_to_json(p.*) from profile p;
                  row_to_json                   
------------------------------------------------
 {"id":1,"name":"John","birthday":"1986-03-29"}
 {"id":2,"name":"Jack","birthday":"1991-03-29"}
(2 rows)

然后将这些json个对象聚合成一个数组:

postgres=# select json_agg(row_to_json(p.*)) from profile p;
                                             json_agg                                             
--------------------------------------------------------------------------------------------------
 [{"id":1,"name":"John","birthday":"1986-03-29"}, {"id":2,"name":"Jack","birthday":"1991-03-29"}]
(1 row)

更简单,您可以只使用聚合,它会为您完成所有转换:

postgres=# select json_agg(p.*) from profile p;
                     json_agg                      
---------------------------------------------------
 [{"id":1,"name":"John","birthday":"1986-03-29"}, +
  {"id":2,"name":"Jack","birthday":"1991-03-29"}]
(1 row)

(没关系 + 符号,它不是 json 的一部分。)