Search code examples
oracle-databaseplsql

Looping Through JSON Array Elements in PL/SQL With Single Key


How do I loop through elements below when the JSON only has single key value in PL/SQL? I know how to stringify it but I do not know how to loop each of them. My code below

declare
    l_json_in clob;
    l_json_obj json_object_t;
    l_json_arr json_array_t;
    l_json_out clob;
begin
    l_json_in := '{"List": ["abc","xyz","edf","cbz"]}';
    
    l_json_obj := json_object_t.parse(l_json_in);
    l_json_arr := l_json_obj.get_array('List');
    
    l_json_out := l_json_arr.stringify;

    dbms_output.put_line(l_json_out);

end;

Expected output:

abc
xyz
edf
cbz


Solution

  • alternative approach, using for loop:

    declare
        l_json_in clob;
        l_json_obj json_object_t;
        l_json_arr json_array_t;
        l_json_out clob;
    begin
        l_json_in := '{"List": ["abc","xyz","edf","cbz"]}';
        
        l_json_obj := json_object_t.parse(l_json_in);
        l_json_arr := l_json_obj.get_array('List');
        
        FOR i IN 0 .. l_json_arr.get_size - 1 LOOP
            dbms_output.put_line(l_json_arr.get_string(i));
        END LOOP;
    end
    ;
    

    nb: this assume all elements are strings