Return results of a sql query as JSON in oracle 12c

后端 未结 9 1630
误落风尘
误落风尘 2020-11-29 05:42

Background

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,

9条回答
  •  日久生厌
    2020-11-29 06:35

    You can use the xmltype to convert the result of an SQL into XML and JSON. See the following article for the solution which will work for Oracle since version 9. You can also download the package itstar_xml_util:

    http://stefan-armbruster.com/index.php/12-it/pl-sql/12-oracle-xml-and-json-goodies

    A simple example with the emp table:

    declare
      l_sql_string varchar2(2000);
      l_xml        xmltype;
      l_json       xmltype;
    begin
      l_sql_string := 'select a.empno, a.ename, a.job from emp a';
    
      -- Create the XML from SQL
      l_xml := itstar_xml_util.sql2xml(l_sql_string);
    
      -- Display the XML
      dbms_output.put_line(l_xml.getclobval());
    
      l_json := itstar_xml_util.xml2json(l_xml);
      -- Display the JSON
      dbms_output.put_line(l_json.getclobval());  
    end;
    

    The result looks like this:

    {"ROWSET": [
        {
          "EMPNO": 7839,
          "ENAME": "KING",
          "JOB": "PRESIDENT"
        },
        {
          "EMPNO": 7698,
          "ENAME": "BLAKE",
          "JOB": "MANAGER"
        },
    [...]
        {
          "EMPNO": 7934,
          "ENAME": "MILLER",
          "JOB": "CLERK"
        }
      ]}
    

提交回复
热议问题