jsonoracle-databasefunctionoracle12ckeyvaluepair

ORACLE - JSON To Key Value Pair Table


Is there any way to obtain a table with key/value pairs from a CLOB Json Column?

The idea here is to get these values, on a dynamic way. Because the CLOB column does not always contain the same structure.

I've created a function that does this, however since it literally parses the json string, when we use it in a table with many records its very slow. And by very slow I mean like 2-5 records per second, i know it's terrible.

The Oracle tools (v.12c) do not provide a dynamic way to obtain the json tags/values, we have always to specify the paths.

I've been digging all around without any luck. Any thoughts?


Solution

  • 12.2 contains a set of PL/SQL objects that can be used to build a DOM like structure of a JSON document. You can then extract key lists etc using methods on the objects. Look in the 12.2 doc for JSON_OBJECT_T, JSON_ARRAY_T etc which can be used like this..

    SQL> create or replace type NV_PAIR_T as object (
      2    NAME  VARCHAR2(32),
      3    VALUE VARCHAR2(32)
      4  )
      5  /
    
    Type created.
    
    SQL> create or replace type NV_PAIR_TABLE as TABLE of NV_PAIR_T
      2  /
    
    Type created.
    
    SQL> create or replace function GET_KEY_VALUES(P_JSON_DOC VARCHAR2)
      2  return NV_PAIR_TABLE PIPELINED
      3  as
      4    JO JSON_OBJECT_T := JSON_OBJECT_T(P_JSON_DOC);
      5    JO_KEYS JSON_KEY_LIST := JO.get_keys();
      6  begin
      7
      8    for i in 1..JO_KEYS.count loop
      9      pipe row (NV_PAIR_T(JO_KEYS(i),JO.get_string(JO_KEYS(i))));
     10    end loop;
     11  end;
     12  /
    
    Function created.
    
    SQL> select *
      2   from TABLE(GET_KEY_VALUES('{"A":"AA", "B":"BB", "C":"CC"}'))
      3  /
    A                                AA
    B                                BB
    C                                CC
    
    SQL>
    

    Does this help