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

后端 未结 9 1639
误落风尘
误落风尘 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:20

    The release 12.2 includes new capabilities for generating JSON documents directly from SQL queries. The easiest way to achieve the goal is to use the functions: JSON_OBJECT and 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;
    

    Result:

            RN JSON_DOC                                                                        
    ---------- ---------------------------------------------------------
             2 [{"col1":1,"col2":"value 1"},{"col1":2,"col2":"value 2"}] 
    

    Test with large amount of data:

    select rn, length (json_doc) json_size, json_doc from (
        
        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"},
    

    On the slow test machine it took ~1 sec. to create 5,6M JSON.


    In the release 19c the syntax of the the function JSON_OBJECT is simplified.
    The query above will look now like this:

    select json_arrayagg (  
        json_object (*) returning clob   
    ) as json_doc  
    from tab;
    

    On Live SQL.

提交回复
热议问题