12.2 版包含直接从 SQL 查询生成 JSON 文档的新功能。实现目标最简单的方法是使用函数:JSON_OBJECT 和 JSON_ARRAYAGG。
create table tab as
select level col1, 'value '||level col2 from dual connect by level <= 2
/
select max (rownum) rn, json_arrayagg (
json_object (
key 'col1' value col1,
key 'col2' value col2
) format json returning clob
) as json_doc
from tab;
结果:
RN JSON_DOC
---------- ---------------------------------------------------------
2 [{"col1":1,"col2":"value 1"},{"col1":2,"col2":"value 2"}]
用大量数据进行测试:
select rn, length (json_doc) json_size, json_doc from (
<query mentoined above here>
cross join (select dummy from dual connect by level <= 1e5)
);
RN JSON_SIZE JSON_DOC
---------- ---------- ---------------------------------------------------------
200000 5600001 [{"col1":1,"col2":"value 1"},{"col1":2,"col2":"value 2"},
在慢速测试机器上大约需要 1 秒。创建 5,6M JSON。
在 19c 版中,函数 JSON_OBJECT is simplified 的语法。
上面的查询现在看起来像这样:
select json_arrayagg (
json_object (*) returning clob
) as json_doc
from tab;
开启Live SQL。