在 oracle 12c 中将查询的输出转换为 json

nav*_*igh 2 oracle plsql oracle-sqldeveloper

我有一个查询,输出是这样的:

    1  2 3 4 5 6 7 8 9 10 11 12 13
    -  - - - - - - - - -   -  - -    
    40 20 22 10 0 0 0 0 0 0 0 0 0
Run Code Online (Sandbox Code Playgroud)

我想将输出转换为一列,该列如下所示:

    output
    -----------
 {"1":40,"2":20,"3":22,"4":10,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0}
Run Code Online (Sandbox Code Playgroud)

tha*_*ith 6

您可以在 SQL Developer 中使用 JSON 格式“技巧”。

在此处输入图片说明

完整场景:

CREATE TABLE JSON_SO (
    "1"   INTEGER,
    "2"   INTEGER,
    "3"   INTEGER,
    "4"   INTEGER,
    "5"   INTEGER,
    "6"   INTEGER
);

INSERT INTO JSON_SO VALUES (
    40,
    20,
    22,
    10,
    0,
    0
);

select /*json*/ * from json_so;
Run Code Online (Sandbox Code Playgroud)

使用 F5 执行时的输出(作为脚本执行):

{
   "results":[
      {
         "columns":[
            {
               "name":"1",
               "type":"NUMBER"
            },
            {
               "name":"2",
               "type":"NUMBER"
            },
            {
               "name":"3",
               "type":"NUMBER"
            },
            {
               "name":"4",
               "type":"NUMBER"
            },
            {
               "name":"5",
               "type":"NUMBER"
            },
            {
               "name":"6",
               "type":"NUMBER"
            }
         ],
         "items":[
            {
               "1":40,
               "2":20,
               "3":22,
               "4":10,
               "5":0,
               "6":0
            }
         ]
      }
   ]
}
Run Code Online (Sandbox Code Playgroud)

请注意,JSON 输出通过 SQL Developer 发生在客户端(这也适用于 SQLcl),我使用https://jsonformatter.curiousconcept.com/格式化了 JSON 输出以在此处显示

这将适用于 SQL Developer 支持的任何版本的 Oracle 数据库,而JSON_OBJECT()函数是在 Oracle Database 12cR2 中引入的 - 如果您希望将 DB 格式的结果设置为 JSON。