Skip to main content

A single query to decompose JSON using the APEX_JSON package, part 1

Updated 7 min readMarkdown
A single query to decompose JSON using the APEX_JSON package, part 1

Sometimes I want to examine in detail a JSON document that is stored in the database. I just want an overview of all the fields in the document, possibly with their values. The JSON document itself can be deeply nested, but I would want a query result with just field and value. And I don't want to install any objects in the database (and sometimes I can't, for example in the production database). Could I use the APEX_JSON package for that? In this two-part series I will offer two solutions for this. Today I will discuss the first solution.

Part 1: The APEX_JSON package variable

The APEX_JSON package contains the PARSE procedure, which decomposes the JSON and puts the fields into the package variable G_VALUES. This variable is of type APEX_JSON.T_VALUES, an associative array of the T_VALUE object type with a VARCHAR2 index.

Because I don't want to install any objects, I would want to use an inline function in my query. And to return multiple rows I would have to use an inline table function. Unfortunately, I cannot use the APEX_JSON.T_VALUES as a return type for the function. I have tried several options, but only types defined as an object in the database are accepted as a return type, package defined types raise an invalid datatype error. Luckily, APEX has the APEX_T_VARCHAR2 type available, and that will do the trick. So, in the inline table function, I have to decompose the JSON, loop through the G_VALUES table and put the values into an APEX_T_VARCHAR2 type. Then I return them to the query, which just selects from the function. The basic version will then be like this:

with function get_jsonvalues(in_json in clob) return apex_t_varchar2 as
   l_values  apex_t_varchar2 := apex_t_varchar2();
   l_idx varchar2(32767);
begin
   apex_json.parse(in_json);
   l_idx := apex_json.g_values.first;
   while l_idx is not null
   loop
      l_values.extend;
      l_values(l_values.count) := l_idx;
      l_idx := apex_json.g_values.next(l_idx);
   end loop;
   return l_values;
end;
select * 
  from get_jsonvalues((select json_column
                         from my_table
                        where id = 1)
                     );

To test this query, I created a table in my schema:

create table my_table(id number primary key, json_column clob);

And I filled it with two sample JSONs from a publicly available API, in this case the Harry Potter API (https://hp-api.onrender.com/):

declare
  l_json clob;
begin
  apex_session.create_session(p_app_id => 100, p_page_id => 1, p_username => 'DUMMY');
  l_json := apex_web_service.make_rest_request(p_url => 'https://hp-api.onrender.com/api/character/9e3f7ce4-b9a7-4244-b709-dae5c1f1d4a8'
                                              ,p_http_method => 'GET');
  insert into my_table (id, json_column) values (1, l_json); 
  l_json := apex_web_service.make_rest_request(p_url => 'https://hp-api.onrender.com/api/characters'
                                              ,p_http_method => 'GET');
  insert into my_table (id, json_column) values (2, l_json); 
end;
/

When I execute the query for the first row (just one character, Harry himself), I get the following results:

COLUMN_VALUE          
----------------------
.
[1]
[1].actor
[1].alive
[1].alternate_actors
[1].alternate_names
[1].alternate_names[1]
[1].alternate_names[2]
[1].alternate_names[3]
[1].alternate_names[4]
[1].ancestry
[1].dateOfBirth
[1].eyeColour
[1].gender
[1].hairColour
[1].hogwartsStaff
[1].hogwartsStudent
[1].house
[1].id
[1].image
[1].name
[1].patronus
[1].species
[1].wand
[1].wand.core
[1].wand.length
[1].wand.wood
[1].wizard
[1].yearOfBirth

29 rows selected. 

I indeed get all the fields from the JSON, including the enclosing array (denoted as ".") and the object in the array (denoted as "[1]"), and including all nested fields like "[1].wand.length". But I also see that the fields are sorted alphabetically, instead of in the order that they have in the original JSON. When I execute the query on the second row (where the JSON is an array of 437 objects) the first object that is returned is 100, then 101, after 109 comes 10 etcetera. When we realize that the g_values array that is used by the APEX_JSON package is an index by varchar2 table, it is clear that when looping through the values of the array it will always be alphabetically sorted. Unfortunately, there is no way to loop through the values in the order that they were inserted in the g_values array.

Adding the values

As I stated in the beginning, apart from the fields I also want to list the values. A limitation of the APEX_T_VARCHAR2 type is that it is a table of only one VARCHAR2 field. So, using APEX_T_VARCHAR2 I have to concatenate field and value in the function, using a separator, and then separate these in the query, using the same separator. To be sure to have the same separator in both function and query I will pass it as a function parameter.

The values can be retrieved from the G_VALUES table, depending on the kind (which is part of the T_VALUE object type). For a number this would be the NUMBER_VALUE field, for a varchar2 the VARCHAR2_VALUE field. For an array the NUMBER_VALUE field holds the array length. The documentation of the APEX_JSON types can be found here.

I now arrive at the following query:

with function get_jsonvalues(in_json      in clob
                            ,in_separator in varchar2) return apex_t_varchar2 as
   l_values  apex_t_varchar2 := apex_t_varchar2();
   l_idx varchar2(32767);
begin
   apex_json.parse(in_json);
   l_idx := apex_json.g_values.first;
   while l_idx is not null
   loop
      l_values.extend;
      case apex_json.g_values(l_idx).kind
         when apex_json.c_null then
            l_values(l_values.count) := l_idx || in_separator;
         when apex_json.c_true then
            l_values(l_values.count) := l_idx || in_separator || 'true';
         when apex_json.c_false then
            l_values(l_values.count) := l_idx || in_separator || 'false';
         when apex_json.c_number then
            l_values(l_values.count) := l_idx || in_separator || apex_json.g_values(l_idx).number_value;
         when apex_json.c_varchar2 then
            l_values(l_values.count) := l_idx || in_separator || apex_json.g_values(l_idx).varchar2_value;
         when apex_json.c_object then
               l_values(l_values.count) := l_idx || in_separator || '{OBJECT}';
         when apex_json.c_array then
               l_values(l_values.count) := l_idx || in_separator || 'ARRAY[' || apex_json.g_values(l_idx).number_value || ']';
         when apex_json.c_clob then
            l_values(l_values.count) := l_idx || in_separator || 'clob';
      end case;
      l_idx := apex_json.g_values.next(l_idx);
   end loop;
   return l_values;
end;
sep as (select '==' arator from dual)
select substr(column_value,1,instr(column_value,sep.arator,1)-1) json_path
     , substr(column_value,instr(column_value,sep.arator,1)+length(sep.arator))   value
  from sep
 cross 
  join get_jsonvalues((select json_column
                         from my_table
                        where id = 1)
                     , sep.arator
                     );
💡
The separator should be a character, or multiple characters, which is not part of any of the fields in the JSON.

Executing this query on my example table yields:

JSON_PATH              VALUE                                 
---------------------- --------------------------------------
.                      ARRAY[1]                              
[1]                    {OBJECT}                              
[1].actor              Daniel Radcliffe                      
[1].alive              true                                  
[1].alternate_actors   ARRAY[0]                              
[1].alternate_names    ARRAY[4]                              
[1].alternate_names[1] The Boy Who Lived                     
[1].alternate_names[2] The Chosen One                        
[1].alternate_names[3] Undesirable No. 1                     
[1].alternate_names[4] Potty                                 
[1].ancestry           half-blood                            
[1].dateOfBirth        31-07-1980                            
[1].eyeColour          green                                 
[1].gender             male                                  
[1].hairColour         black                                 
[1].hogwartsStaff      false                                 
[1].hogwartsStudent    true                                  
[1].house              Gryffindor                            
[1].id                 9e3f7ce4-b9a7-4244-b709-dae5c1f1d4a8  
[1].image              https://ik.imagekit.io/hpapi/harry.jpg
[1].name               Harry Potter                          
[1].patronus           stag                                  
[1].species            human                                 
[1].wand               {OBJECT}                              
[1].wand.core          phoenix tail feather                  
[1].wand.length        11                                    
[1].wand.wood          holly                                 
[1].wizard             true                                  
[1].yearOfBirth        1980                                  

29 rows selected. 

Using an alternative type

Of course, using the APEX_T_VARCHAR2 type, and concatenating and afterwards separating the fields is bit involved. Therefore, I went looking for another existing type that could be used. One possible type is the (APEX provided) WWV_FLOW_T_TEMP_LOV_DATA type, which is a table of WWV_FLOW_T_TEMP_LOV_VALUE objects. The definition of this object is

Name         Null? Type           
------------ ----- -------------- 
INSERT_ORDER       NUMBER         
DISP               VARCHAR2(4000) 
VAL                VARCHAR2(4000) 

The object contains two VARCHAR2 fields, suitable for our field and value columns, and a number field, which could hold the "kind" information (which is a number from 1 through 8). Using this type the query can be much simpler:

with function get_jsonvalues(in_json in clob) return wwv_flow_t_temp_lov_data as
   l_value   wwv_flow_t_temp_lov_value;
   l_values  wwv_flow_t_temp_lov_data := wwv_flow_t_temp_lov_data();
   l_idx varchar2(32767);
begin
   apex_json.parse(in_json);
   l_idx := apex_json.g_values.first;
   while l_idx is not null
   loop
      l_value := wwv_flow_t_temp_lov_value( apex_json.g_values(l_idx).kind
                                          , l_idx
                                          , coalesce(apex_json.g_values(l_idx).varchar2_value, to_char(apex_json.g_values(l_idx).number_value))
                                          );
      l_values.extend;
      l_values(l_values.count) := l_value;
      l_idx := apex_json.g_values.next(l_idx);
   end loop;
   return l_values;
end;
select disp as json_path
     , case insert_order when 1 then 'null'
                         when 2 then 'true'
                         when 3 then 'false'
                         when 4 then 'number'
                         when 5 then 'varchar2'
                         when 6 then '{OBJECT}'
                         when 7 then '[ARRAY]'
                         when 8 then 'clob'
                         else '?' end as kind
     , val as value
  from get_jsonvalues((select json_column
                         from my_table
                        where id = 1)
                     );
💡
The WWV_FLOW_T_TEMP_LOV_DATA is not documented, so using this holds the risk that it will not be available in a future version of APEX. The releases I tested are 23.2 and 24.2.

Conclusion

Using the APEX_JSON package and an inline table function, it is easy to write a query to decompose JSON. Nothing has to be installed in the database (of course having APEX installed is a prerequisite). One drawback of the method used is that the order of the original JSON is not preserved. In part 2 of this series, I will explain an alternative method, where the resulting order is the same as that of the original JSON.

No comments yet. Be the first to comment.