在 oracle 12c 中将 sql 查询的结果作为 JSON 返回

2021-12-06 00:00:00 json oracle12c oracle

背景

我需要从 Oracle 获取几千行并将它们转换为 JSON 以在 SlickGrid 中使用.目前我正在获取 PHP 中的行,使用 iconv 将其从 ISO 转换为 UTF-8,并使用 json_encode 导出到 json.整个操作在 DB 端大约需要 1 秒,生成 JSON 需要 5 秒.太长了.

I need to fetch a few thousands rows from Oracle and convert them to JSON for use in SlickGrid. Currently I am fetching the rows in PHP, converting it from ISO to UTF-8 with iconv and exporting to json with json_encode. The whole operation takes about 1 second on DB side and 5 seconds to generate JSON. It is way to long.

问题

我已经读到 Oracle 12c 支持 JSON,但我找不到我需要的确切内容.

I have read that Oracle 12c supports JSON, but I cannot find exactly what I need.

有没有办法以json格式返回标准sql查询的结果?

Is there a way to return the result of a standard sql query in a json format?

据说我想发出类似这样的查询:

supposedly I would like to issue a query similar to this:

SELECT * from table AS JSON

并接收一个类似于此的有效 json:

and receive a valid json similar to this:

[{"col1": "value1", "col2": 2}, {"col1": "valueOfRow2", "col2": 3}]

重要的是,我需要为我转义 unicode 序列,因为我在客户端使用 ISO-8859-2 字符集,而 JSON 必须采用 UTF-8 或转义序列.

An important thing is that I need to have the unicode sequences escaped for me, as I use ISO-8859-2 charset on the client side, and JSON have to be in either UTF-8 or have the sequences escaped.

推荐答案

Oracle 12c 版本 12.1.0.2(最新版本截至 11.11.2014)添加了 JSON 支持:https://docs.oracle.com/database/121/NEWFT/chapter12102.htm#BGBGADCC

Oracle 12c version 12.1.0.2 (the latest version as of 11.11.2014) adds JSON support: https://docs.oracle.com/database/121/NEWFT/chapter12102.htm#BGBGADCC

它自 10 月 17 日起可用.https://blogs.oracle.com/db/entry/oracle_database_12c_release_1

It's been available since October 17th. https://blogs.oracle.com/db/entry/oracle_database_12c_release_1

如果您无法修补/使用该版本,则可以使用 Lewis Cunningham 和 Jonas Krogsboell 编写的优秀软件包:PL/JSON* http://pljson.sourceforge.net/

If you are unable to patch/work with that version there is an excellent package written by Lewis Cunningham and Jonas Krogsboell: PL/JSON * http://pljson.sourceforge.net/

这是一个很好的包(我已经在许多数据库安装中使用了它).

It's an excellent package (I have used it in numerous database installations).

所包含的示例很好,涵盖了大多数场景.

The examples included are good and cover most scenarios.

declare 
  ret json;
begin
  ret := json_dyn.executeObject('select * from tab');
  ret.print;
end;
/

相关文章