oracle 在PL/SQL中使用单个键循环遍历JSON数组元素

4c8rllxm  于 2023-10-16  发布在  Oracle
关注(0)|答案(2)|浏览(187)

当JSON在PL/SQL中只有一个键值时,如何循环下面的元素?我知道如何将其字符串化,但我不知道如何循环它们中的每个。下面是我的代码

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;

预期输出:
ABC
xyz
EDF
CBZ

aiqt4smr

aiqt4smr1#

另一种方法,使用for循环:

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:假设所有元素都是字符串

fhg3lkii

fhg3lkii2#

我找到了答案:

with json as(select '{"List": ["abc","xyz","edf","cbz"]}' txt
from dual)
select value val
from json_table((select txt from json), '$.List[*]'
        columns(value PATH '$')
)
;

相关问题